繁体   English   中英

如何获取 Datagridview Combobox 所选项目的文本?

[英]How to get the TEXT of Datagridview Combobox selected item?

如何获取DataGridView内的组合框选定项文本 我尝试使用以下代码:

dataGridView1.Rows[1].Cells[1].Value.ToString()

但是,这给出了与此单元格关联的值,而不是组合框选定项文本。 我也试过这个:

DataGridViewComboBoxCell cell = dataGridView1[1,1] as DataGridViewComboBoxCell;
string value = cell.Value.ToString();

但是,这也没有帮助。

我会很感激你的帮助。 提前致谢!

编辑:

假设我们有一个组合框,文本为NoYes ,值分别为 0 和 1。 当组合框更改时,我想在这里得到文本YesNo 但我得到的是使用上述代码的值 0/1。 希望这能让事情变得清楚。

更新:

好的,所以我一直在研究这个问题,经过大量努力并在我的同事的帮助下,我已经能够解决问题并获得所需的解决方案:

这是解决方案:

string SelectedText = Convert.ToString(dataGridView1.Rows[0].Cells[1].FormattedValue.ToString());

要在 DataGridView 中获取组合框的选定值和选定文本,请尝试以下代码

string SelectedText = Convert.ToString((DataGridView1.Rows[0].Cells["dgcombocell"] as DataGridViewComboBoxCell).FormattedValue.ToString());
int SelectedVal = Convert.ToInt32(DataGridView1.Rows[0].Cells["dgcombocell"].Value);

我设法以这种方式从单元格中提取该字符串值:

DataGridViewComboBoxCell dgvcmbcell = dataGridView1[1, 0] as DataGridViewComboBoxCell;
String text = dgvcmbcell.EditedFormattedValue.ToString();

解决这个问题的最简单方法是使用调试器并查看 dgvcmdcell 对象。 在此您将找到可扩展节点“base”。 展开它并浏览它,您将找到所需的任何信息。

要访问 datagridview 中当前选定的文本,您需要引用 Combobox 列的CurrencyManager CurrencyManager与金钱无关,而是管理列与其数据源之间的绑定。 CurrencyManager可以告诉您组合框的当前选择是什么。

代码:

    CurrencyManager cm = (CurrencyManager)DataGridView1.BindingContext[((System.Windows.Forms.DataGridViewComboBoxColumn)DataGridView1.Columns[0]).DataSource];

注意:没有必要将列转换为组合框,我只是这样做是为了向您显示我传入的列。我使用索引 0 但使用任何索引是组合框列的实际索引。

现在使用货币管理器,您可以访问该列的数据网格的当前选择(因为这是您传入的列)。

    cm.Current; //returns the current selection whatever that is

所以在我的例子中,组合框列的数据源是一个名为 Choice 的类,choice 如下所示:

    public class Choice
    {
            public string Text
            {
                get;
                set;
            }
    }

当我访问 cm.Current 属性时,它将返回选择类的一个实例,我现在可以访问我的选择类的Text属性以查看选择了什么值。 显然,您必须根据您的特定情况进行调整。 我希望这有帮助。

也试试这个:

DataGridView.CurrentRow.Cells(Column.name).EditedFormattedValue.ToString()

EditedFormattedValue对象在DataGridView给出单元格的当前格式化值,无论单元格是被编辑还是处于编辑模式。 DataGridView捕获ComboBox选择或任何单元格值更方便。

你可以试试这个:-

dataGridView1.CurrentRow.Cells[0].Value.ToString();

索引您需要查看的单元格的列,以您的ComboBoxColumn的索引为准。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM