2011-04-07 11 views
0

我有收到BindingList如何使用BindingList自動生成的列對DataGridView中的數據進行排序?

dataGrid.DataSource = new BindingList<Value>(ValueList); 

它經過DataGridView我嘗試設置SortMode

dataGrid.Columns.OfType<DataGridViewColumn>().ToList() 
    .ForEach(c => 
    { 
     c.SortMode = DataGridViewColumnSortMode.Automatic; 
    }); 

斷點不會停止,但我DataGridView不可排序......我試試點擊標題並沒有任何反應。

這些列是自動生成的,我能做些什麼來排序數據?

+0

檢查[this](http://stackoverflow.com/questions/3770857/how-do-i-implement-automatic-sorting-of-datagridview)out – V4Vendetta 2011-04-07 05:03:01

回答

0

我相信問題是您需要製作一個自定義綁定列表來實現必要的排序功能,以便DataGridView知道如何對每列進行排序。

這篇文章提供了越來越分揀工作良好的信息:

http://xiaonanstechblog.blogspot.com/2009/03/how-to-enable-column-sorting-on.html

如果你想既過濾和排序,你可能想要做的IBindingListView界面的自定義實現:

http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglistview.aspx

0

DataGridView綁定到數據源DataView,BindingSource,Table,DataSet +「tablename」)在所有情況下,都參照DataView。獲取參考這個數據視圖,並設置排序(和過濾)如你所願:

DataView dv = null; 
CurrencyManager cm = (CurrencyManager)(dgv.BindingContext[dgv.DataSource, dgv.DataMember]); 

if (cm.List is BindingSource) 
{ 
    // In case of BindingSource it may be chain of BindingSources+relations 
    BindingSource bs = (BindingSource)cm.List; 
    while (bs.List is BindingSource) 
    { bs = bs.List as BindingSource; } 

    if (bs.List is DataView) 
    { dv = bs.List as DataView; } 
} 
else if (cm.List is DataView) 
{ 
    // dgv bind to the DataView, Table or DataSet+"tablename" 
    dv = cm.List as DataView; 
} 

if (dv != null) 
{ 
    dv.Sort = "somedate desc, firstname"; 
    // dv.Filter = "lastname = 'Smith' OR lastname = 'Doe'"; 

    // You can Set the Glyphs something like this: 
    int somedateColIdx = 5; // somedate 
    int firstnameColIdx = 3; // firstname 
    dgv.Columns[somedateColIdx].HeaderCell.SortGlyphDirection = SortOrder.Descending; 
    dgv.Columns[firstnameColIdx].HeaderCell.SortGlyphDirection = SortOrder.Ascending; 
} 

注:排序和篩選使用列名對應列名的DataTable,在 列名DataGridView是用於在dgv中顯示單元格的控件的名稱。 你可以在數據視圖中使用這樣的列名:

string colName = dgv.Columns[colIdx].DataPropertyName 

的你要如何跟蹤排序列Depends中(colSequence,COLNAME,遞增/遞減,dgvColIdx),你可以決定如何排序構建和篩選表達式並在dgv中設置SortGlyph(爲簡單起見,我製作了硬編碼)。

相關問題