.Net DataGridView “Index 0 does not have a value.”

别等时光非礼了梦想. 提交于 2020-01-13 04:09:59

问题


I am having trouble with a DataGridView. I have a collection of 3 Items bound to the grid, when trying to delete one of the items and reload the grid.

If have code of

If (dlg.ShowDialog() = DialogResult.OK) Then
     'Show dialog with grid on it
End If

On the opened dialog, I delete an item from the grid (which should in turn, delete the item from the collection, and re-load the grid), and it returns to the "If (dlg.show..." line, with the error of

"A first chance exception of type 'System.IndexOutOfRangeException' occurred in System.Windows.Forms.dll

Additional information: Index 2 does not have a value. "

(I have break into debugger set on for common language runtime errors)

I can understand this error if i were trying to access any cells, row or columns, but im not, and then I would expect the exception to stop on the line of code that is trying to access this grid data, not the "If (dlg.ShowDialog()... " line

Any ideas? Cheers


回答1:


I have discovered that if you add in

DataGridView.DataSource = Nothing
DataGridView.Refresh()

before resetting the grid to the collection (with the deleted item removed)

DataGridView.DataSource = MyCollection

It works like a charm. Still interested as to why you have to do this.




回答2:


It is possible that since you are showing a modal dialog, the error that is thrown is shown there. Have you tried to set a break point in the line of code that actually does the deleting from the grid/collection to see if the error is coming from that?




回答3:


This seems a .Net bug, i created a test program, it still fails, but i got a workaround by adding Null check and items count before data source binding:

If MyCollection IsNot Nothing AndAlso MyCollection.Count > 0 Then
    DataGridView.DataSource = MyCollection
End If


来源:https://stackoverflow.com/questions/1630200/net-datagridview-index-0-does-not-have-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!