我的Winforms应用程序中有一个datagridview。 用户可以单击datagridview上的任意位置 然后单击按钮以对该数据行执行操作 但是,为了做到这一点,我需要从该行恢复ID 现在请记住用户可能没有点击ID列 所以SelectedCell.Value对我来说没用,
我尝试过以下代码
DataGridViewRow row = dataIPs.SelectedRows[0];
DataGridViewCell cell = row.Cells[0];
string value = cell.Value.ToString();
但这会产生Out of Bounds错误。
无论用户实际选择哪一列,如何从datagridview的特定列获取值。
最终对我有用的代码如下:
DataGridViewRow row = dataIPs.CurrentCell.OwningRow;
string value = row.Cells["IPID"].Value.ToString();
答案 0 :(得分:2)
如果没有选择任何行,您似乎正在尝试访问SelectedRows
集合。
DataGridView
的默认选择模式为CellSelect
,在此模式下,当您单击某个单元格时,未选择任何行。
您需要更改选择模式或以其他方式获取所需的行。
您可以将选择模式更改为FullRowSelect
,可以在设计人员或代码中完成:
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
或者您可以从中访问所选单元格和行:
DataGridViewRow row = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex];
或者像这样:
DataGridViewRow row = dataGridView1.CurrentCell.OwningRow;
答案 1 :(得分:0)
尝试从event args获取值。
答案 2 :(得分:0)
将SelectionMode属性设置为FullRowSelect。这是SelectedRow工作所必需的
答案 3 :(得分:0)
您还可以尝试在datagridview中添加带按钮的列。之后,您可以从datagridview中捕获事件“CellContentClick”,该事件在eventargs中具有“RowIndex”和“ColumnIndex”属性。