I have a pretty standard DataGridView and have already used
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False
in order ensure the entire row is selected.
Situation : I need to obtain the selected row in order to load the data in the row to another screen to "Modify" the data. I am using the following to get the Selected Row.
Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
Try
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView2.Rows(e.RowIndex)
GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row
MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo)
'textboxTst.Text = row.Cells("Description").Value.ToString
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Question : The problem is that most of the time when one clicks on the data within the DGV the code above is run and sets the e.RowIndex - BUT when I hit any white space on the row nothing happens and so results in the problem of using the previous row selected, which is in fact the wrong row.?
Any ideas would be appreciated. Thanks in advance
I think what you are looking for is DataGridView CellClick instead of CellContentClick. CellContentClick does not fire when white space around the cell content is clicked.
Private Sub DataGridView2_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellClick
Try
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView2.Rows(e.RowIndex)
GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row
MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo)
'textboxTst.Text = row.Cells("Description").Value.ToString
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub