可恶的AutoSizeColumnMode和DataError
项目中DataGridView中使用了DataGridViewComboBoxColumn,不记得在哪里看到AutoSizeColumnMode设置成allcells,AutoSizeRowsMode=None,觉得蛮好的,结果把所有表单的DGV都设置成这样,不幸的意外发生了:结果关闭表单的时候就会发生DataError错误,说什么DataGridViewComboBoxCell的值不合法。
这时候还不知道哪里出了问题,以为绑定的顺序有问题,结果无奈之中把所有DGV加了个空的DataError 处理。
后来不甘心,到MSDN论坛上一查,原来碰到这个问题的不止我一个:http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=157106&SiteID=1&PageID=2
下面是DataGridView Program Manager的解答:
The issue is that the Form's dispose method is first disposing the datasource that the combobox column is using before it is disposing the DataGridview. This is the same as not databinding the combobox column at all. This only causes a problem when autosizing the rows or autosizing the combobox column since removing the combobox column's datasource causes the row/column to perform autosize layout. As part of the layout, the combobo cell needs to retrieve the FormattedValue, which raises the DataError since the cell cannot find a match in the combobox (since the combobox column's datasource is now null).
和处理办法:
The easiest way to fix this is to change the autosize mode of the grid in the form's dispose method. Alternatively you can manually databind the combo box column, including manually creating the BindingSource. This will allow you to manually dispose the combobox column's binding source on your own -- after the grid has already disposed.
Currently we do not have any way to specify any dependency for disposing, but in 2005 we did create better support for dependencies when initializing controls/components. Sounds like we need to create some new support to deal with this type of problem.
I've opened a bug to address this issue hoping that we can do something in the next version.
提示:
以后遇到问题多泡泡MSDN的论坛,比国内的好上一百倍,因为有微软的测试或者设计人员及时解答您的提问。
一蓑烟雨任平生