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

8

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

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

我尝试了以下方法:

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

这个问题一直出现错误。

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

非常感谢您的任何帮助。

4个回答

13

我刚刚在一个示例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);
}
请注意,为使此方法有效,您需要删除设计师生成的事件附件,并引用设计师生成的方法。

刚注意到你提到了rowenter事件 - 我现在正在检查。 - David Hall
已经检查过了,我所说的对于RowEnter事件也适用——代码运行良好,不过我想知道是否有更好的事件可供使用,比如SelectionChanged。 - David Hall
我认为这可能与我绑定到DVG的方式有关。在您看来,最好的方法是什么?我已经尝试了EF,尝试使用DVG任务进行设置,现在正在尝试DataAdapter。 - Noelle
当它从填充DVG到甚至加载表单之前的这一行时,它们都在单独的方法中,每个方法只有一行。 - Noelle
这些方法在这种情况下是等效的。问题出现在你附加SelectionChanged事件时。我已经编辑了我的答案。 - David Hall
我使用了SqlDataAdapter,将OnRowEnterEvent更改为SelectionChangedEvent,现在它运行良好。谢谢David。你的建议真的很有帮助。 - Noelle

2
这也可以运行:

这也可以运行:

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

1
当您单击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; }

0

我尝试的方法很好用,但绑定调用了选择更改事件。所以我按照David Hall建议的做法(附加和分离事件),并将其放在try catch块中,现在它完美地工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接