Olá, estou tentando ativar ordenação quando se clica na header de um datagrid, mas estou tomando esse erro:
System.InvalidOperationException: 'O controle DataGridView deve ser associado a um objeto IBindingList para ser classificado.'
O código para ativar essa ordenação é assim:
private void dataGridView1_ColumnHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn newColumn = dataGridView1.Columns[e.ColumnIndex];
DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
ListSortDirection direction;
if (oldColumn != null)
{
if (oldColumn == newColumn &&
dataGridView1.SortOrder == SortOrder.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
direction = ListSortDirection.Ascending;
oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
}
}
else
{
direction = ListSortDirection.Ascending;
}
dataGridView1.Sort(newColumn, direction);
newColumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
}
private void dataGridView1_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
column.SortMode = DataGridViewColumnSortMode.Programmatic;
}
}