Когда DataGridView связывается с DataSource ( DataView, BindingSource, Table, DataSet + "tablename" ), во всех случаях оно ссылается на DataView . Получите ссылку на этот 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;
}
Примечание: Имена столбцов, используемые в Sort и Filter, соответствуют именам столбцов в DataTable ,
Имена столбцов в DataGridView - это имена элементов управления, используемые для отображения ячеек в dgv.
Вы можете получить имя столбца, используемое в DataView следующим образом:
string colName = dgv.Columns[colIdx].DataPropertyName
Зависит от того, как вы хотите отслеживать отсортированные столбцы (colSequence, colName, asc / desc, dgvColIdx), вы можете решить, как создать выражение сортировки и фильтрации и установить SortGlyph в dgv (я сделал жесткий код для простоты).