在實例中,將從 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();
}