c# – 获取DataGridView中特定列的值
发布时间:2020-12-15 17:26:22 所属栏目:百科 来源:网络整理
导读:我的 Winforms应用程序中有一个datagridview. 用户可以单击datagridview上的任意位置 然后单击按钮以对该数据行执行操作 但是,为了做到这一点,我需要从该行恢复ID 现在请记住用户可能没有点击ID列 所以SelectedCell.Value在这里对我没用 我试过以下代码 Data
我的
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(); 解决方法
当没有选择任何行时,您似乎正在尝试访问SelectedRows集合.
DataGridView的默认选择模式是CellSelect,在此模式下单击单元格时,不选择任何行. 您需要更改选择模式或以其他方式获取所需的行. >您可以将选择模式更改为FullRowSelect,可以在设计器或代码中完成: dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; >或者您可以从中访问所选单元格和行: DataGridViewRow row = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex]; 或者像这样: DataGridViewRow row = dataGridView1.CurrentCell.OwningRow; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |