以下代码抛出带有上述消息的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控件的单元格。那我为什么得到这个例外呢?
非常感谢您的意见。
答案 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中的所有列并创建新的列。所以我不能挂在重新绑定的列引用上。