Vb.net – Select first row of DataGridView and display cell contents in text boxes

datagridvb.net

I am working on a small VB application that retrieves customer data (ID, Name, Last Name, Purchase Detail) from an SQL table and displays it on a DataGridView.

There are 4 text fields on the same form, and my goal is that every time a DataGridView row is clicked on, the contents of its cells will be displayed on those fields.

So far everything´s working fine, except for this: Once the form finishes loading and the DataGridView is displayed, the first row of the grid is selected (highlighted) but its data is not displayed on the text fields.

If I click once on that row, the data IS displayed.

So my problem is that I have not been able to programatically make the data from the 1st row to be automatically displayed on the text fields once the form finished loading.

I have tried

Form1.DataGrid1.Rows(0).Selected = true

and also

Form1.DataGrid1.Rows.GetFirstRow(DataGridViewElementStates.Visible)

but neither code works. The 1st row is highlighted but the data is not displayed on the text fields unless I click on the row.

I was thinking about programatically simulate a mouse click on the 1st row, but I have no idea if that´s a feasible solution.

Any help you can provide will be much appreciated. Many thanks in advance!

Randy

Best Answer

The reason that selecting the row simply highlights it is that that is exactly what selection is. You can select multiple rows at the same time but obviously you couldn't display data from multiple rows in your other controls at the same time.

How exactly are you loading the data into the grid? If you're binding it via a BindingSource, as you should be, then what you should actually be doing is setting the Current or Position of the BindingSource. If the other controls are bound too then that will have the desired effect.

Otherwise, what you need to do is to set the CurrentRow property, which you can only do by assigning a cell in that row to the CurrentCell property.

Related Topic