【问题标题】:how to retrieve the value of the value-tem pair in a combo box in c#.net?如何在 c#.net 的组合框中检索 value-tem 对的值?
【发布时间】:2012-07-05 07:13:10
【问题描述】:

我有这个表单,我需要在其中使用数据库中的文本值对填充组合框,以便我可以在对数据库的更新查询中使用该值

我发现了一些方法,它使用一个类来制作同时具有文本和值的对象:

class RequestType
    {
        public string Text { get; set; }
        public string Value { get; set; }

        public RequestType(string text, string val)
        {
            Text = text;
            Value = val;
        }

        public override string ToString()
        {
            return Text;
        }

我像这样将它们添加到组合框中

RequestType type1 = new RequestType("Label 1", "Value 1");
            RequestType type2 = new RequestType("Label 2", "Value 2");

            comboBox1.Items.Add(type1);
            comboBox1.Items.Add(type2);

            comboBox1.SelectedItem = type2;

现在我不知道如何检索所选项目的值,即选择了id标签1,它必须返回value1,如果选择了标签2,它返回value2,

请帮忙???提前谢谢xx

【问题讨论】:

    标签: c# combobox


    【解决方案1】:

    组合框的 Items 集合的类型为 ObjectCollection,因此当您使用

    设置项目时
    comboBox1.Items.Add(type1); 
    

    您正在向集合中添加一个 RequestType 对象。
    现在,当您想从该集合中检索单个选定项目时,您可以使用这样的语法

    RequestType t = comboBox1.SelectedItem as RequestType;
    

    理论上,(当您完全控制组合框项的添加时)您可以避免检查使用 as 关键字应用的转换是否成功,但情况并非如此,因为 SelectedItem 可能为 null 并且因此,测试总是一个好习惯

       if(t != null)
       {
           Console.WriteLine(t.Value + " " + t.Text);
       }
    

    【讨论】:

    • 正确,但您应该检查 t 是否为空... :)
    • 对不起@Marco,考试来了
    【解决方案2】:
    RequestType type = (RequestType)comboBox1.SelectedItem;
    

    现在,所选项目的值 = type.Value

    【讨论】:

    • @Marco 实际上我并没有编写完整的代码 sn-p,只是展示了如何获取所选项目的值...但是任何方式这始终是重要的事情检查为...;)
    【解决方案3】:

    您可以将 comboBox1.SelectedItem 转换为您的类型 RequestType,然后您可以读取它的属性。

    【讨论】:

      【解决方案4】:

      我认为你可以使用:

      if (combobox1.SelectedItem != null)
          val2 = (comboBox1.SelectedItem as RequestType).Value;
      

      string val2 = combobox1.SelectedItem != null ?
                        (comboBox1.SelectedItem as RequestType).Value :
                        null;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        相关资源
        最近更新 更多