简体   繁体   English

DataGridView中当前选定行的索引

[英]Index of Currently Selected Row in DataGridView

It's that simple. 就这么简单。 How do I get the index of the currently selected Row of a DataGridView ? 如何获取当前所选的DataGridView Row的索引? I don't want the Row object, I want the index (0 .. n). 我不想要Row对象,我想要索引(0 .. n)。

There is the RowIndex property for the CurrentCell property for the DataGridView. DataGridView的CurrentCell属性有RowIndex属性。

datagridview.CurrentCell.RowIndex

Handle the SelectionChanged event and find the index of the selected row as above. 处理SelectionChanged事件并查找所选行的索引,如上所示。

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

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

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

dataGridView1.SelectedRows.Select(r => r.Index);
dataGridView1.SelectedRows[0].Index;

Here find all about datagridview C# datagridview tutorial 这里找到关于datagridview C#datagridview教程的所有内容

Lynda 林达

try this it will work...it will give you the index of selected row index... 试试这个它会工作...它会给你所选行索引的索引...

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

try this 试试这个

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
}

I modified @JayRiggs' answer, and this works. 我修改了@JayRiggs的答案,这很有效。 You need the if because sometimes the SelectedRows may be empty, so the index operation will throw a exception. 您需要if因为有时SelectedRows可能为空,因此索引操作将引发异常。

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

Try it: 试试吧:

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

I hope it will help you. 我希望它会对你有所帮助。

Try DataGridView.CurrentCellAddress . 尝试DataGridView.CurrentCellAddress

Returns: A Point that represents the row and column indexes of the currently active cell. 返回:表示当前活动单元格的行索引和列索引的Point。

EG Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 ) EG选择第一列和第五行,然后你会回来:Point(X = 1,Y = 5)

You can try this code : 你可以试试这段代码:

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

I used if get row value is clicked: 我使用了如果点击获取行值:

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
}

Try the following: 请尝试以下方法:

int myIndex = MyDataGrid.SelectedIndex;

This will give the index of the row which is currently selected. 这将给出当前所选行的索引。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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