0

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

OK - I know this is an old post, but I read the above and came up with this code, so I thought I would share it.

  Private Function TryReturnString(ByRef obj As Object) As String
    Dim rtn As String = String.Empty
    If obj IsNot Nothing Then
      rtn = obj.ToString
    End If
    Return rtn
  End Function

Or for the above:

  Private Function TryReturnIndex(ByRef curRow As DataGridViewRow) As Integer
    Dim rtn As Integer = 0
    If curRow IsNot Nothing Then
      rtn = curRow.Index
    End If
    Return rtn
  End Function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.