获取DataGridView中选定行的单元格内容

本文关键字:单元格 DataGridView 获取 | 更新日期: 2023-09-27 17:50:42

我有一个从数据库填充的DataGridView

我试图获得在RowEnter事件上选择的行内容。我已经将网格的选择模式设置为FullRowSelect

我已经试过了:

int orderId = (int)dgUnprocessedCards.Rows[dgUnprocessedCards.SelectedCells[0].RowIndex].Cells[0].Value;

this一直抛出错误

索引超出范围。必须非负且小于集合的大小。

获取DataGridView中选定行的单元格内容

我刚刚在一个样本datagridview应用程序中尝试了这个,它工作得很好,所以一定有什么事情发生了,你还没有告诉我们。

首先要做的是把你的一个大语句分解成离散的小语句,这样你就可以确切地看到错误在哪里。

为了调试,你可以把上面的代码重写成这样:
var cellindex = dgUnprocessedCards.SelectedCells[0].RowIndex;           
var cellcollection = dgUnprocessedCards.Rows[cellindex].Cells[0];
int orderId = (int)dgUnprocessedCards.Value;

同时,你应该能够做以下事情来实现你想要的:

int orderId = (int)dataGridView1.SelectedRows[0].Cells[0].Value;

它使用SelectedRows集合这是更简洁的一种从datagridview访问选中项的更常用的方式。

最后,您可能希望对值的强制转换进行检查,因为value不一定是int类型。比如:

int orderid;
if (!int.TryParse(cellcollection.Value.ToString(), out orderid))
{
    // Some logic to deal with the fact that Value was not an int
}

何时引发SelectionChanged事件?

现在-正如你提到的,你的选择改变事件触发加载数据到网格。这似乎不会在我的测试版本中引起问题,但可能是您的问题的一部分。

发生这种情况的原因与您正在使用的数据源类型无关,而与您何时附加选择更改事件处理程序有关。这是因为数据绑定导致引发选择更改事件。

如果你为DataBindingComplete事件添加了一个事件处理程序,并在那里附加了你的SelectionChanged或RowEnter事件处理程序,你应该看不到在数据绑定期间调用的处理程序。

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    this.dataGridView1.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowEnter);
    this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
}

请注意,您需要删除设计器生成的事件附件,并引用设计器生成的方法才能正常工作。

这也可以:

int orderId = (int)dgUnprocessedCards.SelectedCells[0].OwningRow.Cells[0].Value;

你可以得到特定的列值当你点击Datagridview列

private void DataGridview_CellContentClick(object sender, 
DataGridViewCellEventArgs e) { int col = e.ColumnIndex; int row = 
e.RowIndex; Var value=DataGridview.Rows[row].Cells[col].Value; }

我尝试做的工作很好,但绑定正在调用选择更改事件。所以我做了David Hall建议的(附加和分离事件),我也把它放在try catch块中,现在它工作得很好。