0
votes

Hi I use following code to display selected row data of a datagridview in text boxes. The problem I have is that when user click an empty row of the datagrid view there is an error.

Please help

Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    Dim i As Integer
    i = DataGridView1.CurrentRow.Index
    Me.txtBoxServTypeID.Text = DataGridView1.Item(0, i).Value
    Me.txtBoxServiceType.Text = DataGridView1.Item(1, i).Value
    Me.txtBoxCapacity.Text = DataGridView1.Item(2, i).Value
End Sub
3

3 Answers

0
votes

on an empty row the row index is -1, thus trying to access DataGridView1.Item(0, -1).Value causes the error

0
votes

Updated the code. I'm unable to test it at the moment because of a windows update causing freeze problems on my pc so I may have errors in there.

Try

Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    Dim i As Integer
    i = DataGridView1.CurrentRow.Index
    If String.IsNullOrEmpty(CStr(DataGridView1.Item(0, i).Value)) orelse String.IsNullOrEmpty(CStr(DataGridView1.Item(1, i).Value)) orelse String.IsNullOrEmpty(CStr(DataGridView1.Item(2, i).Value))Then
        Messagebox.Show("Empty row clicked - no data returned")
    else
        Me.txtBoxServTypeID.Text = DataGridView1.Item(0, i).Value
        Me.txtBoxServiceType.Text = DataGridView1.Item(1, i).Value
        Me.txtBoxCapacity.Text = DataGridView1.Item(2, i).Value
    End If
End Sub

This way at least the user has some idea what they did wrong. If this is all the code in your click handler then that may suffice, but if you have other code, you may need to handle the lack of data returned by the If statement

0
votes

you can update your code like this :

Dim i As Integer
i = DataGridView1.CurrentRow.Index
if Not isDBNull(DataGridView1.Item(0, i).value) then

Me.txtBoxServTypeID.Text = DataGridView1.Item(0, i).Value
Me.txtBoxServiceType.Text = DataGridView1.Item(1, i).Value
Me.txtBoxCapacity.Text = DataGridView1.Item(2, i).Value
end if