[英]Order datagridview descending with linq
我嘗試訂購我的datagridview但不能。 在網絡上我找到並修改了這個:
List<DataGridViewRow> q = (from item in dataGridView1.Rows.Cast<DataGridViewRow>()
orderby item.Cells[0].Value descending
select item).ToList<DataGridViewRow>();
但它不起作用,因為我不知道如何將此列表分配給我的datagridview的數據源。
也許,這不是正確的形式。 在其他項目中,我將數據放在我的datagridview列表中,然后在列表中執行linq查詢,它就可以了。 在datagridview中怎么樣?
只需使用DataGridView.Sort()
方法:
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);
如果您決定使用LINQ(可能更復雜的排序,或以其他方式操作數據),最好采用原始數據源(即列表),就像您之前所說的那樣。
我認為你不能以通用的方式做你想做的事情,因為DataSource
是一個object
,所以最終你需要將DataSource
回你用來填充DataGridView
的原始數據類型。在第一位。
嘗試這個,
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.