对datagridview c#进行排序 - 附加信息:DataGridView控件必须绑定到要排序的IBindingList对象

时间:2017-06-17 23:36:56

标签: c# sorting datagridview

这是来自https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick(v=vs.110).aspx

的代码
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn newColumn = dataGridView1.Columns[e.ColumnIndex];
DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
ListSortDirection direction;

// If oldColumn is null, then the DataGridView is not sorted.
if (oldColumn != null)
{
    // Sort the same column again, reversing the SortOrder.
    if (oldColumn == newColumn &&
        dataGridView1.SortOrder == SortOrder.Ascending)
    {
        direction = ListSortDirection.Descending;
    }
    else
    {
        // Sort a new column and remove the old SortGlyph.
        direction = ListSortDirection.Ascending;
        oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
    }
}
else
{
    direction = ListSortDirection.Ascending;
}

// Sort the selected column.
dataGridView1.Sort(newColumn, direction);
newColumn.HeaderCell.SortGlyphDirection =
    direction == ListSortDirection.Ascending ?
    SortOrder.Ascending : SortOrder.Descending;
}

private void dataGridView1_DataBindingComplete(object sender,
    DataGridViewBindingCompleteEventArgs e)
{
    // Put each of the columns into programmatic sort mode.
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        column.SortMode = DataGridViewColumnSortMode.Programmatic;
    }
}

请告诉我为什么在运行此代码时出现此错误: 类型为' System.InvalidOperationException'的未处理异常发生在System.Windows.Forms.dll

附加信息:DataGridView控件必须绑定到要排序的IBindingList对象。

0 个答案:

没有答案