【问题标题】:C# - retrieve the selected value from a comboboxC# - 从组合框中检索选定的值
【发布时间】:2013-02-26 07:39:03
【问题描述】:

我有一个带有ValueMember = IDDisplayMember = Name 的组合框。我需要与该名称关联的值,因此我执行以下操作:

if (cboTypeOfMaterial.SelectedIndex != -1)
            {
                string temp = cboTypeOfMaterial.SelectedValue.ToString();
                //More code here...
            }

它将ID 值作为字符串返回。例如 - “7”。

如果我尝试:

if (cboTypeOfMaterial.SelectedIndex != -1)
                {
                    string temp = cboTypeOfMaterial.DisplayMember.ToString();
                    //More code here...
                }

我得到了字符串Name,这是关键。

而我需要的是获取所选元素Name的值

【问题讨论】:

  • 简单地 cboTypeOfMaterial.SelectedItem.ToString() 也应该可以工作。试一试。

标签: c# .net winforms visual-studio-2010


【解决方案1】:

SelectedValue 将返回在ValueMember 中定义的属性的值,SelectedItem 将返回被选中的整个对象,如果您想获得除 SelectedValue 之外的另一个值,则必须强制转换为ComboBox 中的对象然后您可以访问您的 Name 属性。

string temp = (cboTypeOfMaterial.SelectedItem as YourObjectType).Name;

【讨论】:

  • 谢谢,这很有效,而且是新东西,所以我要使用它!
【解决方案2】:

尝试通过SelectedItem 访问元素,这将为您提供与该条目关联的整个对象,然后您可以访问所需的属性,在您的情况下为ID

【讨论】:

    【解决方案3】:

    您可以做的是为组合框中的条目创建一个自定义类。这可能看起来像:

    public class ComboBoxItem
    {
        public string Display { get; set; }
        public int Id { get; set; }
        public override string ToString()
        {
            return this.Display;
        }
    }
    

    那么就可以通过以下代码获取选中的ComboBoxItem:

    ComboBoxItem cbi = (ComboBoxItem)cboTypeOfMaterial.SelectedValue;
    if(cbi != null)
       // Access the Property you need
    

    【讨论】:

      【解决方案4】:

      我知道这是一个老问题,但我很惊讶没有人提到:

      ComboBox1.GetItemText(ComboBox1.SelectedItem)
      

      它返回所选项目的文本表示(即DisplayMember),并且在涉及数据绑定ComboBox 或任何ListControl 的情况下很有帮助。

      【讨论】:

        【解决方案5】:
        string temp = cboTypeOfMaterial.ValueMember.ToString();
        

        【讨论】:

          【解决方案6】:

          我认为您也可以使用 Text 属性,但这不是一个好的解决方案。更好的解决方案是@dutzu 的建议。

          string temp = cboTypeOfMaterial.Text;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-08-18
            • 2013-05-21
            • 2021-07-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多