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

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

  • 使用 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.wpf123.com/news/?202.html 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值