Jeffrey Lopez Jeffrey Lopez - 2 months ago 12
Vb.net Question

VB.Net - "NullReferenceException was unhandled by user code"

Here is the code in my DataGridView's SelectionChanged event:

Dim a as Integer
a = DataGridView1.CurrentRow.Index 'this certain line contains the error
TextBox1.Text = DataGridView1.Item(0,a).Value
'and all that jazz


The code runs, but when a cell is clicked followed by any column header, the error shows up.

I tried placing this block of code in another event called CellContentClick but clicking on the cells in the datagridview is not that responsive as compared to SelectionChanged.

Any ideas on how to fix this?

Answer

The DataGridView or the DataGridView1.CurrentRow are null ...

To avoid the error you can simply ensure that they are not null before attempting to access them :

Dim a as Integer = 0
If DataGridView1 IsNot Nothing AndAlso DataGridView1.CurrentRow IsNot Nothing Then 
 a = DataGridView1.CurrentRow.Index 'this certain line contains the error
EndIf