2014-02-07 106 views
0

我嘗試訂購我的datagridview,但不能。在網絡上,我發現和修改這個:訂購datagridview與linq降序

List<DataGridViewRow> q = (from item in dataGridView1.Rows.Cast<DataGridViewRow>() 
          orderby item.Cells[0].Value descending 
          select item).ToList<DataGridViewRow>(); 

但它不工作,因爲我不知道如何向此列表分配給我的datagridview的數據源。

也許,這不是正確的形式。在其他項目中,我將數據放在列表中的datagridview中,然後在列表中執行linq查詢,這是行得通的。在datagridview中如何?如果你決定使用LINQ(也許更復雜的順序,或者操縱在一些其他的方式中的數據),這將會是最好行事原始來源

dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending); 

回答

1

試試這個,

List<DataGridViewRow> q = (from item in dataGridView1.Rows.Cast<DataGridViewRow>() 
          orderby item.Cells[0].Value descending 
          select item).ToList<DataGridViewRow>(); 

dataGridView1.DataSource = q.Select(x => x.DataBoundItem).Cast<Employee>().ToList(); 

對於投我已經通過了Employee,但你需要傳遞的,而不是Employee

類或者你可以綁定數據源不投,像

dataGridView1.DataSource = q.Select(x => x.DataBoundItem).ToList(); 
+0

謝謝你!它的作品 – WFgo

+0

@WFgo,你好,歡迎:) –

1

只需使用DataGridView.Sort()方法的數據(即列表),就像你之前說過的那樣。

我不認爲你可以做任何你想在一個通用類的辦法做,因爲DataSourceobject,所以最終你需要投DataSource回到任何原始數據類型是你使用首先填充DataGridView

+0

是,這不是最好的例子。抱歉。無論如何,我可以分配到數據源列表? – WFgo