我的
Winforms应用程序中有一个datagridview.
用户可以单击datagridview上的任意位置
然后单击按钮以对该数据行执行操作
但是,为了做到这一点,我需要从该行恢复ID
现在请记住用户可能没有点击ID列
所以SelectedCell.Value在这里对我没用
用户可以单击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();
解决方法
当没有选择任何行时,您似乎正在尝试访问SelectedRows集合.
DataGridView的默认选择模式是CellSelect,在此模式下单击单元格时,不选择任何行.
您需要更改选择模式或以其他方式获取所需的行.
>您可以将选择模式更改为FullRowSelect,可以在设计器或代码中完成:
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
>或者您可以从中访问所选单元格和行:
DataGridViewRow row = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex];
或者像这样:
DataGridViewRow row = dataGridView1.CurrentCell.OwningRow;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。