简体   繁体   English

如何获取datagridviewcomboboxcolumn的ValueMember的值

[英]How to get value of ValueMember of datagridviewcomboboxcolumn

Friends, I'm using datagridviewcomboboxcolumn as column index 1 in my datagridview. 朋友,我将datagridviewcomboboxcolumn用作datagridview中的列索引1。 I've fetched data from access database table and populated the datagridviewcomboboxcolumn by following manner: 我已经从访问数据库表中获取数据,并通过以下方式填充了datagridviewcomboboxcolumn:

    for (int i = 0; reader.Read(); i++)
        {
            cmbBusCode.Items.Add(reader["BUSINESS_CODE"] + "-" + reader["BUSINESS_DESCRIPTION"]);
            cmbBusCode.ValueMember = "BUSINESS_CODE";
        }

Then I'm writing this: 然后我写这个:

        cmbBusCode.DisplayIndex = 1;
        cmbBusCode.Width = 200;
        cmbBusCode.Name = "Code";
        cmbBusCode.HeaderText = "Code";

And adding this column as 并将此列添加为

    dgView.Columns.Add(cmbBusCode);

Combobox is being populated and I can select any one from the list. 组合框正在填充,我可以从列表中选择任何一个。 Now when I'm saving data I want to get the ValueMember of the selected item. 现在,当我保存数据时,我想获取所选项目的ValueMember。 To get this value I'm using following code but It's giving the string representation of the field "BUSINESS_CODE" not the value..Please help me so that get ValueMemeber of the selected item.. 要获得此值,我正在使用以下代码,但给出的是字段“ BUSINESS_CODE”的字符串表示形式,而不是值。.请帮助我,以获取所选项目的ValueMemeber。

    foreach (DataGridViewRow row in dgView.Rows)
    {
        string cd = row.Cells["Code"].Value.ToString();
    }

The "item" you are adding to the column doesn't have a "BUSINESS_CODE" column (essentially, the item as you add it is simply a string), so that doesn't work. 您要添加到该列中的“项目”没有“ BUSINESS_CODE”列(实际上,添加时该项目只是一个字符串),因此不起作用。

What you need to do is assign items that contain multiple columns. 您需要做的是分配包含多列的项目。 One must be the BUSINESS_CODE column (as it is this column you want to be the value for the underlying field in the DataGridView ), the other should be a display column that contains the concatenated value you're adding at the moment ( DisplayMember and ValueMember ). 一个必须是BUSINESS_CODE列(因为您想将此列作为DataGridView基础字段的值),另一个必须是一个显示列,其中包含您当前要添加的串联值( DisplayMemberValueMember )。

Easiest would be to create a typed data set, add a table that contains the two columns I described and fill the table with the data from the data reader. 最简单的方法是创建一个类型化的数据集,添加一个包含我描述的两列的表,并用数据读取器中的数据填充该表。

Then, add the table as the data source for the column. 然后,将该表添加为该列的数据源。

You can try adding a DataGridViewComboBoxCell instead of a string to the cmbBusCode.Items collection. 您可以尝试向cmbBusCode.Items集合中添加DataGridViewComboBoxCell而不是string You can then specify Value in the cell. 然后,您可以在单元格中指定“ Value ”。 I'm not sure if this will work, but it's worth a try. 我不确定这是否行得通,但是值得一试。

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

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