[英]IComparer sort on databound Datagridview
我有一個數據綁定的DataGridView,我試圖使用IComparer進行排序。
當我嘗試應用我的排序時,我收到此錯誤:
DataGridView控件是數據綁定的。 控件不能使用比較器來執行排序操作。
我的排序技術基於此鏈接 。
只是一個FYI我試圖通過使用他們的標簽值來比較位圖。
public int Compare(object x, object y)
{
DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;
// Try to sort based on the tag
int CompareResult = System.String.Compare(
DataGridViewRow1.Cells[1].Tag.ToString(),
DataGridViewRow2.Cells[1].Tag.ToString());
return CompareResult * sortOrderModifier;
}
據我所知,數據綁定DatagridView無法使用鏈接文章中顯示的方法進行排序。
你想要做的是對底層容器進行排序。 如果您使用的是DataTable,則無法直接對其進行排序。
您可以做的是使用Linq的OrderBy並將其傳遞給您的自定義比較器。 之后,在linq查詢上調用AsDataView()並將DataGridView綁定到此DataView。
像這樣的東西:
RowComparer comp = new RowComparer();
var query = northwindDataSet.Customers.AsEnumerable().OrderBy(q => q, comp);
DataView dv = query.AsDataView();
customersBindingSource.DataSource = dv;
請注意,我在這個例子中使用的是DataTable和BindingSource,但你應該明白這一點:-)
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.