在DataGridView的特定列中获取值 [英] Get value in specific column in DataGridView

查看:414
本文介绍了在DataGridView的特定列中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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的特定列中获取值,无论用户实际选择哪一列。



ANSWER



最后为我工作的代码如下:

  DataGridViewRow row = dataIPs.CurrentCell。所有权
string value = row.Cells [IPID]。Value.ToString();


解决方案

您似乎试图访问 SelectedRows 集合当没有行被选中。



$ $ $ $ $ $ $ $ code>是 CellSelect ,而在此模式下,当您单击一个单元格时,不会选择任何行。



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




  • 您可以将选择模式更改为 FullRowSelect 可以在设计器或代码中完成:

      dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 


  • 或者您可以访问所选单元格和行:

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

    或像这样:

      DataGridViewRow row = dataGridView1.CurrentCell.OwningRow; 



I have a datagridview in my Winforms Application. The user can click anywhere on the datagridview And then click a button to perform an action on that datarow However, in order to do this I need to recover the ID from that row Now bearing in mind the user probably hasnt clicked the ID column So SelectedCell.Value is no use to me here

I have tried the following code

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

But this produces an Out Of Bounds error.

How can I obtain the value from a specific column of the datagridview regardless of which column the user actually selects.

ANSWER

The code that worked for me in the end was as follows:

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

解决方案

You appear to be trying to access the SelectedRows collection when no row has been selected.

The default selection mode for the DataGridView is CellSelect and in this mode when you click on a cell no row is selected.

You need to either change the selection mode or get the desired row some other way.

  • 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;
    

这篇关于在DataGridView的特定列中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆