У меня есть форма с сеткой данных.dataGridView привязан к BindingSource:
public class Address
{
public string State { get; set; }
public string City { get; set; }
public string Street { get; set; }
}
this.addressBindingSource.DataSource = typeof(Address);
this.dataGridView1.DataSource = this.addressBindingSource;
Я заполняю DataSource
следующим образом:
addressBindingSource.DataSource = new BindingList<Address>
{
new Address {State = "S1", City = "C1", Street = "S1"},
new Address {State = "S1", City = "C1", Street = "S2"},
new Address {State = "S1", City = "C1", Street = "S3"},
new Address {State = "S1", City = "C2", Street = "S4"},
new Address {State = "S1", City = "C2", Street = "S5"},
new Address {State = "S1", City = "C2", Street = "S6"},
};
Я пытаюсь включить сортировку для этого представления данных.Я установил SortMode
на Programmatic
для всех столбцов dataGridView1.И я добавил обработчик событий для ColumnHeaderMouseClick
:
private Dictionary<int, string> columnIndexPropertyNameDictionary = new Dictionary<int, string>
{
{0, "State"},
{1, "City"},
{2, "Street"},
};
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex < 0)
return;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
if (i == e.ColumnIndex)
continue;
dataGridView1.Columns[i].HeaderCell.SortGlyphDirection = SortOrder.None;
}
var column = dataGridView1.Columns[e.ColumnIndex];
if (column.SortMode != DataGridViewColumnSortMode.Programmatic)
return;
var sortGlyphDirection = column.HeaderCell.SortGlyphDirection;
switch (sortGlyphDirection)
{
case SortOrder.None:
case SortOrder.Ascending:
addressBindingSource.Sort = columnIndexPropertyNameDictionary[e.ColumnIndex] + " ASC";
column.HeaderCell.SortGlyphDirection = SortOrder.Descending;
break;
case SortOrder.Descending:
addressBindingSource.Sort = columnIndexPropertyNameDictionary[e.ColumnIndex] + " DESC";
column.HeaderCell.SortGlyphDirection = SortOrder.Ascending;
break;
}
}
Сортировка по-прежнему не работает.Что я делаю не так?