Question : FormClosing causes mscorlib.dll "Index was out of range exception".... why

I have a windows forms application written in vb.net.  All of a sudden I am getting an exception that does not make sense to me.

I have a main form.  From this main form I open  anotherform using form.ShowDialog()
From this form I then show another form also using form.ShowDialog as I want each one to be the child of the previous form.
I  then have a Form Closing event from the last opened form that updates a datagridview with a value but I then get an Index out of range.

I have verified that the row index is correct, however I can see that the datagridview says it only has 0 rows when it actually has 2.  So when I try to update row One index it crashes.

This seems to be a UI issue.  Any thoughts?

Answer : FormClosing causes mscorlib.dll "Index was out of range exception".... why

You can alleviate this problem greatly by passing in the "parent" form to ShowDialog() like this:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
Public Class Form2

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim F3 As New Form3
        F3.ShowDialog(Me) ' <-- passing in the current instance of Form2 to our dynamic instance of Form3
    End Sub

End Class

Public Class Form3

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' cast the "owner" to the actual instance of Form2 so we can use it:
        Dim F2 As Form2 = CType(Me.Owner, Form2)
        F2.Text = "Can you hear me now?"
    End Sub

End Class
Random Solutions  
 
programming4us programming4us