DataGridView中当前选定行的索引

时间:2010-08-26 18:13:49

标签: c# .net winforms datagridview

就这么简单。如何获取Row当前所选DataGridView的索引?我不想要Row对象,我想要索引(0 .. n)。

12 个答案:

答案 0 :(得分:148)

DataGridView的RowIndex属性有CurrentCell属性。

datagridview.CurrentCell.RowIndex

处理SelectionChanged事件并找到所选行的索引,如上所述。

答案 1 :(得分:36)

使用DGV的SelectedRows集合中的Index属性:

int index = yourDGV.SelectedRows[0].Index;

答案 2 :(得分:7)

dataGridView1.SelectedRows[0].Index;

或者,如果您想使用LINQ并获取所有选定行的索引,您可以执行以下操作:

dataGridView1.SelectedRows.Select(r => r.Index);

答案 3 :(得分:6)

dataGridView1.SelectedRows[0].Index;

此处找到有关datagridview C# datagridview tutorial

的所有信息

林达

答案 4 :(得分:3)

试试这个它会起作用......它会给你所选行索引的索引...

int rowindex = dataGridView1.CurrentRow.Index;
MessageBox.Show(rowindex.ToString());

答案 5 :(得分:2)

试试这个

bool flag = dg1.CurrentRow.Selected;

if(flag)
{
  /// datagridview  row  is  selected in datagridview rowselect selection mode

}
else
{
  /// no  row is selected or last empty row is selected
}

答案 6 :(得分:1)

试试DataGridView.CurrentCellAddress

  

返回:表示当前活动单元格的行索引和列索引的Point。

E.G。选择第一列和第五行,然后你会回来:Point(X = 1,Y = 5)

答案 7 :(得分:1)

我修改了@ JayRiggs'回答,这很有效。您需要if,因为有时SelectedRows可能为空,因此索引操作会抛出异常。

if (yourDGV.SelectedRows.Count>0){
    int index = yourDGV.SelectedRows[0].Index;
}

答案 8 :(得分:1)

试一试:

int rc=dgvDataRc.CurrentCell.RowIndex;** //for find the row index number
MessageBox.Show("Current Row Index is = " + rc.ToString());

我希望它会对你有所帮助。

答案 9 :(得分:0)

您可以尝试以下代码:

int columnIndex = dataGridView.CurrentCell.ColumnIndex;
int rowIndex = dataGridView.CurrentCell.RowIndex;

答案 10 :(得分:0)

我使用了如果点击获取行值:

private void dataGridView_Product_CellClick(object sender, DataGridViewCellEventArgs e){
    int rowIndex;
    //rowIndex = e.RowIndex; //Option 1
    //rowIndex= dataGridView_Product.CurrentCell.RowIndex; //Option 2
    rowIndex = dataGridView_Product.CurrentRow.Index; //Option 3
}

答案 11 :(得分:-1)

尝试以下方法:

int myIndex = MyDataGrid.SelectedIndex;

这将给出当前所选行的索引。

希望这有帮助