3

Problem

I encountered this error whenever components.dispose() is called in a windows form with DataGridView.

The following exception occured in the DataGridView:

System.IndexOutOfRangeException: Index 0 does not have a value. at System.Windows.Forms.CurrencyManager.get_item(Int32 Index) at System.Windows.Forms.DataGridViewDataConnection.GetError(Int32 rowIndex)

To replace this default dialog please handle the DataError event.

Solution

My solution was calling DataGridView.dispose() method before components.dispose() is called as advised from here

Question

I'm still not sure why we need to call dispose method on DataGridView. If base.dispose() is called instead of components.dispose() and we don't call DataGridView.dispose(), this error wouldn't occur...which is logical as base.dispose() disposes everything.

Why doesn't components.dispose() call DataGridView.dispose()?

John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67
  • 1
    DataGridView is a [component.](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview%28v=vs.110%29.aspx) allright. Who calls the Dispose? – TaW May 06 '16 at 08:25
  • @TaW U mean which function? It is run after FormClosed() is called – John Evans Solachuk May 06 '16 at 08:30
  • Inheritance chain is DataGridView : Control : Component – George Lica May 06 '16 at 08:30
  • @GeorgeLica so DataGridView is a child of component, alright. But why do I have to call DataGridView.dispose() in order to remove the items in it? Wouldn't components.dispose() do the trick? – John Evans Solachuk May 06 '16 at 08:33
  • @Mark Maybe he accidentally removed it from the Controls collection of the form before calling Dispose ... or something very strange is going on. For example, someone has a simmilar problem on Disposing the form (an IndexOutOfRangeException is thrown): https://social.msdn.microsoft.com/Forums/windows/en-US/3b33c7ff-9d85-490f-870d-001d5dd229aa/index-was-out-of-range-on-formdispose?forum=winforms – George Lica May 06 '16 at 08:36
  • [This might be related](https://social.msdn.microsoft.com/Forums/windows/en-US/3b33c7ff-9d85-490f-870d-001d5dd229aa/index-was-out-of-range-on-formdispose?forum=winforms) - Check the answer from nobugz (aka Hans Passant) – Matthew Watson May 06 '16 at 08:46
  • @GeorgeLica and Matthew Watson, I've read his comments but I don't understand how lazy initialization can be the source of this error. Care to explain in your answers to this question? Thanks. – John Evans Solachuk May 06 '16 at 09:11
  • @Mark I've got no idea. I can only suggest that you try the workaround mentioned in that thread to see if it has any effect. – Matthew Watson May 06 '16 at 09:34

0 Answers0