只能在属于DataGridView控件的单元格上执行操作

时间:2009-09-06 23:10:32

标签: .net datagridview

以下代码抛出带有上述消息的InvalidOperationException,我不明白为什么。当用户可能对datagridview的基础数据源进行了更改时,我的代码调用以下方法。目标是使用任何更改的数据更新显示,并保留排序列和顺序。

private void ReloadDataGridBindingListFromDatabase()
        {
            DataGridView dgv = myDataGridViewControl;
            DataGridViewColumn sortedColumn = dgv.SortedColumn;
            SortOrder sortOrder = dgv.SortOrder;

            //do stuff here to refresh dgv.DataSource

            if (sortedColumn != null)
            {
                //this line throws an exception
                sortedColumn.HeaderCell.SortGlyphDirection = sortOrder;
            }

            //etc.
        }

显然,sortedColumn.HeaderCell是属于DataGridView控件的单元格。那我为什么得到这个例外呢?

非常感谢您的意见。

2 个答案:

答案 0 :(得分:2)

我在以下情况遇到此错误: 使用微软样本DataGridViewAutoFilterColumnHeaderCell和 在窗口的DataSource事件中设置DataGridView的{​​{1}}。

如果您将OnLoad绑定到DataGridView DataTable的排序条件(包括DefaultView之一),则会出现此错误。

因此,在设置DataGridViewAutoFilterColumn清除DataSource DataTable上的排序顺序之前,请先解决此问题。

例如:

DefaultView

====================

我尝试了上面提出的解决方案 - 它对我来说并不合适,但它让我走上正轨。我提供了我(非常相似)的解决方案。

// Without this line if the sort included a column that is an
// auto filter column you will get an error
table.DataView.Sort = "";

dataGridView.DataSource = new BindingSource(table, null);

答案 1 :(得分:1)

没关系。我很清楚,重新绑定datagridview的数据源会破坏datagridview中的所有列并创建新的列。所以我不能挂在重新绑定的列引用上。