在DataGridView中获取特定列的值

4

我在我的Winforms应用程序中有一个DataGridView。

用户可以在DataGridView上的任何位置单击,然后单击按钮对该数据行执行操作。

但是,为了做到这一点,我需要从该行恢复ID。

现在请记住,用户可能没有单击ID列。

因此,SelectedCell.Value在这里对我没有用。

我尝试了以下代码:

DataGridViewRow row = dataIPs.SelectedRows[0];
DataGridViewCell cell = row.Cells[0];
string value = cell.Value.ToString();

但这会导致越界错误。

无论用户选择哪一列,我该如何获得datagridview中特定列的值。

答案

最终对我起作用的代码如下:

DataGridViewRow row = dataIPs.CurrentCell.OwningRow;
string value = row.Cells["IPID"].Value.ToString();

越界错误是在什么时候发生的?是在 SelectedRows[0] 还是 Cells[0] 调用时发生的? - SPFiredrake
4个回答

3

当没有选择任何行时,您似乎正在尝试访问SelectedRows集合。

DataGridView的默认选择模式是CellSelect,在此模式下,单击单元格不会选中任何行。

您需要更改选择模式或以其他方式获取所需行。

  • You can change the selection mode to FullRowSelect which can be done in the designer or in code:

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    
  • Or you can access the selected cell and the row from that:

    DataGridViewRow row = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex];
    

    Or like this:

    DataGridViewRow row = dataGridView1.CurrentCell.OwningRow;
    

问题在于右键单击和双击单元格会产生不同的事件。因此,我需要用户能够选择单个单元格。因此,我不能使用fullrow select。我需要一种方法来恢复所选单元格的行索引,而没有可用的mouseeventargs。 - PJW
@PJW 看看第二个选项 - 基于所选单元格选择行。除非您在某处存储鼠标单击位置,否则必须选择某些内容,因为当他们单击按钮时,鼠标显然不再位于网格上。 - David Hall
@PJW,还有一种选择,就是像sickunit建议的那样引入一个按钮类型的列。 - David Hall

0
尝试从事件参数中获取值。

这是一个按钮点击事件 - 这就是我遇到的问题 - 所以事件参数没有rowindex、columnindex等。EventArgs中的'value'将是高亮单元格中的值,而不一定是我想要的列中的值。例如,如果我的网格有4列,则我想要选定行的第一列的值,而不管实际选择了哪一列中的值。 - PJW

0
将 SelectionMode 属性设置为 FullRowSelect。 这是为了 SelectedRow 能够正常工作所必需的。

0

你也可以尝试在你的DataGridView中添加一个带有按钮的列。之后,你可以从你的DataGridView中捕获一个名为"CellContentClick"的事件,该事件在EventArgs中具有"RowIndex"和"ColumnIndex"属性。


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