I want my textboxes to auto fill when I select a row. Here is an example...
ID | Firstname | Lastname |
---|---|---|
2435 | timmy | turner |
I click on row with ID = 1 ---> TextBox1.text = 2435
I have tried
For Each row As DataGridViewRow In DataGridView1.SelectedRows
TextBox1.Text = row.Cells(0).value
Next
I know this is completely wrong but I think I have the right idea.
CodePudding user response:
You have to handle the SelectionChanged
event of the DataGridView.
Private Sub MyDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles MyDataGridView.SelectionChanged
With MyDataGridView
' Ensure one and only one row is selected.
If .SelectedRows IsNot Nothing AndAlso .SelectedRows.Count = 1 Then
Dim row As DataGridViewRow = .SelectedRows(0)
TextBox1.Text = row.Cells(0).Value.ToString()
TextBox2.Text = row.Cells(1).Value.ToString()
End If
End With
End Sub
CodePudding user response:
If you use a BindingSource
, you can apply the same DataSource to several controls and they will remain synced.
The constructor of Binding
takes
- The property you want to bind, in this case
Text
- The source of the data, in this case the BindingSource,
bs
- The field name of the column in the DataTable that you want to bind, in this case
Name
for one andType
for another. (fields in my database table)
As you select rows in the DataGridView, the TextBoxes will sync.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = LoadCoffeeTable()
Dim bs As New BindingSource(dt, Nothing)
DataGridView1.DataSource = bs
TextBox1.DataBindings.Add(New Binding("Text", bs, "Name"))
TextBox2.DataBindings.Add(New Binding("Text", bs, "Type"))
End Sub