简体   繁体   中英

Select first row of DataGridView and display cell contents in text boxes

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´sa feasible solution.

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

Randy

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.

Try this..

 private void DataGridView1_SelectionChanged(object sender, EventArgs e)
    {
      if( DataGridView1.SelectedRows.Count = 0 )
      {
        TextBox1.Value = DataGridView1.SelectedRows(0).Cells(0).Value;
        TextBox2.Value = DataGridView1.SelectedRows(0).Cells(1).Value;
        TextBox3.Value = DataGridView1.SelectedRows(0).Cells(2).Value;
        TextBox4.Value = DataGridView1.SelectedRows(0).Cells(3).Value;
      }
    }

also see this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM