简体   繁体   中英

How to programmatically set focus on a row in a WinForms DataGrid when selecting it?

I have a WinForms DataGrid (not DataGridView). When I manually select a row, the row indicator, shown in the first image below, shows on the selected rows. However, if I set the DataGrid's datasource after a save and programmatically select the second row using: datagrid.Select(1) , the second row gets the highlighted background color but the focus indicator is on the first row as shown in the second image below.

Is there a way to make the selected row get focus and have the indicator display for the row?

在此处输入图像描述

在此处输入图像描述

Since this is the old System.Windows.Forms.DataGrid , the Row selection method is slightly different than the DataGridView's.

You can select a Row, as you're doing, with the Select() method.
This doesn't change the Current Row. To make a Row the Current, you can use the CurrentRowIndex property.
Combined, these two move the selection and set the Current Row.

 // Selects and highlights the Row at index 1
 dataGrid.Select(1);
 // Make the Row at index 1 the Current
 dataGrid.CurrentRowIndex = 1;

Something similar in a DataGridView:
(One of the methods that can be used to achieve this result)

// Move the focus and selects the Row at index 1
dataGridView.Rows[1].Selected = true;
// Make the Row at index 1 the Current setting the CurrentCell property
dataGridView.CurrentCell = dgvTest.Rows[1].Cells[0];

Try this:

dataGridView1.FirstDisplayedScrollingRowIndex = 
                                dataGridView1.Rows[dataGridView1.Rows.Count - 2].Index;

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