當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(爲簡單起見,我製作了硬編碼)。
檢查[this](http://stackoverflow.com/questions/3770857/how-do-i-implement-automatic-sorting-of-datagridview)out – V4Vendetta 2011-04-07 05:03:01