在 DataGrid 控件中显示 SQL Server 数据库中的数据
在实例中,将从 SQL Server 数据库检索数据,并在 DataGrid 控件中显示该数据。 您可以使用 ADO.NET Entity Framework 创建代表数据的实体类,使用 LINQ 编写从实体类中检索指定数据的查询。效果图如下:转载自:http://www.***http://www.***/upFiles/infoImg/2011051775948577.JPG
使用 C# 创建一个新的 WPF 应用程序项目,并将其命名为 DataGridSQLExample。
在解决方案资源管理器中右击您的项目,指向 “添加”,然后选择 “新建项”。
此时将显示“添加新项”对话框。
在“已安装的模板”窗格中,选择 “数据”并在模板列表中选择 “ADO.NET 实体数据模型”。
将文件命名为 ADOTest.edmx,然后单击 “添加”。
将显示实体数据模型向导。
在“选择模型内容”屏幕上,选择 “从数据库生成”,然后单击 “下一步”。
http://www.***/upFiles/infoImg/2011051776011033.JPG
在“选择您的数据连接”屏幕上,提供与 Northwind数据库的连接。
http://www.***/upFiles/infoImg/2011051776232097.JPG
确保名称为 NorthwindEntities 且选中 “将 App.Config 中的实体连接设置另存为”复选框,然后单击“下一步”。
在“选择数据库对象”屏幕中,展开“表”节点,然后选择 “Customers”和 “Products”表。
您可以为所有表生成实体类;但是,在此示例中,只从这两个表检索数据。
http://www.***/upFiles/infoImg/2011051776359169.JPG
单击 “完成”。
“Customers”和 “Products””实体显示在实体设计器中。
http://www.***/upFiles/infoImg/2011051776397473.JPG
XAML:
readonly NorthwindEntities dataEntities = new NorthwindEntities();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ObjectQuery customers = dataEntities.Customers;
var query =
from customer in customers
where customer.City == "London"
orderby customer.CustomerID
select new { customer.CustomerID, customer.CompanyName, customer.ContactName,
customer.ContactTitle };
DataGridTest.ItemsSource = query.ToList();
} 转载自:http://www.***/news/?202.html
页:
[1]