簡體   English   中英

在DataGridView中以編程方式選擇行

[英]Selecting rows programmatically in DataGridView

我希望在某些事件之后選擇之前選定行的行,我的代碼如下所示。

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

執行代碼后,預覽將如下所示。 但我需要得到符號> id = 1272741(藍色選擇)而不是1272737

在此輸入圖像描述

可能你可能已經看過DataGridView.CurrentRow屬性 ,它是一個只讀屬性:

獲取包含當前單元格的行。

但在備注部分,有寫道:

要更改當前行,必須將CurrentCell屬性設置為所需行中的單元格。

另外,從DataGridView.CurrentCell屬性中 ,我們發現:

更改此屬性的值時,SelectionChanged事件發生在CurrentCellChanged事件之前。 此時訪問CurrentCell屬性的任何SelectionChanged事件處理程序都將獲得其先前的值。

因此,您無需實際選擇currentRow因為在設置CurrentCell值時將選擇它(除非您在SelectionChangedCurrentCellChanged事件之間的當前范圍內執行某些代碼)。 嘗試這個:

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

我想你想突出這一行。 請嘗試以下代碼,我認為它可能會有所幫助:

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

請嘗試以下操作來更改當前行。 由於OP對於哪一行應該是新行有點不清楚,我的示例只是顯示從當前行移動到上一行(如果有前一行)。 第一行代碼是可選的。 如果您不想使用FullRowSelect,也可以將col硬編碼為0(或其他某些列)以使用固定列。

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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM