Reputation: 53
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.
Upvotes: 0
Views: 202
Reputation: 15091
If you use a BindingSource
, you can apply the same DataSource to several controls and they will remain synced.
The constructor of Binding
takes
Text
bs
Name
for one and Type
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
Upvotes: 0
Reputation: 6756
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
Upvotes: 3