Fiendcoder
Fiendcoder

Reputation: 33

Populate textboxes when clicking on a row in the DataGridView in VB?

I'm using Visual Studio 2010. I'm having a profiling system for my project and I can now add from VB to SQL using the DataGridView.

What I want to do now is to edit the selected row, when I click the DataGridView and it will populate the textbox. How can I do this?

Upvotes: 2

Views: 3973

Answers (1)

Alex
Alex

Reputation: 4938

You could handle the CellClick event. When you click on the cell of a DataGridView, it will trigger this event.

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
  'Check if the user clicks on a valid row. ie: Not on the row header or column header
  If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 Then
    'Set the textbox text to the specified column's value
    Textbox1.Text = DataGridView1.Rows(e.RowIndex).Cells(0).Value '1st column
    Textbox2.Text = DataGridView1.Rows(e.RowIndex).Cells(1).Value '2nd column

    'Set the textbox3 text to the cell value the user just clicked on
    Textbox3.Text = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
  End If
End Sub

Keep in mind that DataGridView1.Rows(e.RowIndex).Cells(0) will be the first column in your DataGridView (even if it is visible or not).

Upvotes: 2

Related Questions