您的位置:首页 > 数据库

在 DataGrid 控件中显示 SQL Server 数据库中的数据

2011-05-17 21:21 381 查看
在实例中,将从 SQL Server 数据库检索数据,并在 DataGrid 控件中显示该数据。 您可以使用 ADO.NET Entity Framework 创建代表数据的实体类,使用 LINQ 编写从实体类中检索指定数据的查询。效果图如下:转载自:http://www.***



使用 C# 创建一个新的 WPF 应用程序项目,并将其命名为 DataGridSQLExample。

在解决方案资源管理器中右击您的项目,指向 “添加”,然后选择 “新建项”。

此时将显示“添加新项”对话框。

在“已安装的模板”窗格中,选择 “数据”并在模板列表中选择 “ADO.NET 实体数据模型”。

将文件命名为 ADOTest.edmx,然后单击 “添加”。

将显示实体数据模型向导。

在“选择模型内容”屏幕上,选择 “从数据库生成”,然后单击 “下一步”。



在“选择您的数据连接”屏幕上,提供与 Northwind数据库的连接。



确保名称为 NorthwindEntities 且选中 “将 App.Config 中的实体连接设置另存为”复选框,然后单击“下一步”。

在“选择数据库对象”屏幕中,展开“表”节点,然后选择 “Customers”和 “Products”表。

您可以为所有表生成实体类;但是,在此示例中,只从这两个表检索数据。



单击 “完成”。

“Customers”和 “Products””实体显示在实体设计器中。



XAML:
<Window x:Class="DataGridSQLExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Window_Loaded"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid Name="DataGridTest"></DataGrid>
</Grid>
</Window>

readonly NorthwindEntities dataEntities = new NorthwindEntities();

private void Window_Loaded(object sender, RoutedEventArgs e)
{
ObjectQuery<Customers> 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐