2015-09-21 34 views
0

我被卡住了。我想要顯示一個查詢結果到一個數據網格中。如何使用LinqToSQL顯示查詢結果

我已經LinqToSQL類命名爲:linq_to_sql.dbml

我有我的DataGrid:

<DataGrid x:Name="list_clients"></DataGrid> 

這是我的代碼:

linq_to_sqlDataContext db = new linq_to_sqlDataContext(); 
var query = (from c in db.CLIENT select c); 
list_clients.ItemsSource = query; 

但每次我跑我的應用程序時,它不起作用:System.InvalidCastException錯誤

+1

在'list_clients.ItemsSource = query;'上設置一個斷點。然後在此時停止代碼,將鼠標光標放在「查詢」上並查看它的外觀。它需要是一個集合。 – dev1998

+0

如果爲null,那麼我的值爲null,並且類型爲System.Collections.IEnumerable。 – Raphael

+0

你得到查詢爲空? –

回答

2

當前var query不包含您的查詢結果,它仍然以sql格式(您可以在此行放置一個斷點並查看query的值)查詢,直到您將此查詢轉換爲某個集合或數據表。爲了綁定網格,您需要集合類型或數據表。改變這一行:

list_clients.ItemsSource = query; 

list_clients.ItemsSource = query.ToList(); 
+0

添加'query.ToList();'是必需的。 – dev1998

1

我能夠這樣做是爲了填充您的DataGrid:

public WindowDemo01() 
{ 
    InitializeComponent(); // Make sure this occurs first so that your Datagrid is built before your ItemsSource is set. 

    var query = (from c in db.CLIENT select new { Name = c.Name });  

    list_clients.ItemsSource = query.ToList(); 

} 

我使用的字段名= 「姓名」,因爲這是我的桌子了。你可以使用別的東西。您也可以返回多個字段。

確保您的數據庫中的CLIENT表與數據環境設置爲相同。您可能必須使用服務器資源管理器才能獲得所需的內容。

我從來沒有能夠得到你有的System.InvalidCastException錯誤。我懷疑你的應用程序中可能會發生其他事情。