Extracting the content of datagridview cells

pachjo

Well-known member
Joined
Dec 12, 2006
Messages
370
Programming Experience
10+
Where is the best place to put your code to get the row/cell data after a user selects a datagridview row?

I notice that as soon as my app starts the code below fires even before the form opens.

Also I get an error on the first line stating object not set or an error for the second row of index out of range?

I want to store each cell from the selected row into their corresponding string variables.

VB.NET:
Private Sub dgvUndelivered_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgvUndelivered.SelectionChanged

        strDetail = Me.dgvUndelivered.SelectedRows(0).Cells("ORDER").Value

        strDetail = Me.dgvUndelivered.SelectedRows(0).Cells(0).Value

Thnx
 
use "try"

"index out of range" is because your dgv cells having null value at the first load until u fill it, i thought :rolleyes:
so put it in "try"

Try
strDetail = Me.dgvUndelivered.SelectedRows(0).Cells("ORDER").Value

strDetail = Me.dgvUndelivered.SelectedRows(0).Cells(0).Value

Catch ex As Exception

End Try
 
It is in most cases best to avoid TryCatch if you don't need it, like here you can check if there actually is any selected rows before you access them.
VB.NET:
Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles DataGridView1.SelectionChanged
    If Me.DataGridView1.SelectedRows.Count > 0 Then
        Me.Text = Me.DataGridView1.SelectedRows(0).Cells(0).Value
    End If
End Sub
 
Back
Top