简体   繁体   中英

Selecting rows programmatically in DataGridView

I want to select row of previously selected rows after some event my code is as below.

int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex;
//code to execute
dgvIcbSubsInfo.Rows[currentRow].Selected = true;

after executing the code the preview will be as below. but i need to get the symbol > in id = 1272741 (blue selection) and not in 1272737

在此输入图像描述

Probably you might have taken a look at the DataGridView.CurrentRow Property , which is a read-only property:

Gets the row containing the current cell.

But in the remarks section, there is written:

To change the current row, you must set the CurrentCell property to a cell in the desired row.

Also, from the DataGridView.CurrentCell Property , we find out that:

When you change the value of this property, the SelectionChanged event occurs before the CurrentCellChanged event. Any SelectionChanged event handler accessing the CurrentCell property at this time will get its previous value.

So, there is no need that you actually select the currentRow becasue it will be selected when you set the CurrentCell value (unless you have some code to be executed inside the current scope between the SelectionChanged and CurrentCellChanged events). Try this:

//dgvIcbSubsInfo.Rows[currentRow].Selected = true;
dgvIcbSubsInfo.CurrentCell = dgvIcbSubsInfo.Rows[currentRow].Cells[0];

I think you wish to highlight the row. Please try following code, I think it might help:

Color color = dgv.Rows[prevRowIndex].DefaultCellStyle.SelectionBackColor;
dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = color;

Try the following to change the current row. Since the OP is a little unclear as to what row should be the new row, my example simply shows moving from the current row to the previous row (if there is a previous row). The first line of code is optional. You can also hardcode col to 0 (or some other column) to use a fixed column if you don't want to use FullRowSelect.

dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
int row = dataGridView.CurrentCell.RowIndex;
int firstRow = dataGridView.Rows.GetFirstRow(DataGridViewElementStates.None);
if (row != firstRow)
{
  row--;
  int col = dataGridView.CurrentCell.ColumnIndex;
  dataGridView.CurrentCell = dataGridView[col, row];
}

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