带有组合框项目的隐藏 ID? [英] Hidden Id With ComboBox Items?

查看:20
本文介绍了带有组合框项目的隐藏 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何将项目添加到 ComboBox,但是无论如何要为每个项目分配一个唯一的 Id 吗?如果它被选中,我希望能够知道哪个 Id 与每个项目相关联.谢谢!

I know how to add items to a ComboBox, but is there anyway to assign a unique Id to each item? I want to be able to know which Id is associated to each item if it is ever selected. Thanks!

推荐答案

组合框中的项目可以是任何对象类型,显示的值为 ToString() 值.

The items in a combobox can be of any object type, and the value that gets displayed is the ToString() value.

因此,您可以创建一个具有用于显示目的的字符串值和一个隐藏 id 的新类.只需覆盖 ToString 函数即可返回显示字符串.

So you could create a new class that has a string value for display purposes and a hidden id. Simply override the ToString function to return the display string.

例如:

public class ComboBoxItem
{
   string displayValue;
   string hiddenValue;

   // Constructor
   public ComboBoxItem (string d, string h)
   {
        displayValue = d;
        hiddenValue = h;
   }

   // Accessor
   public string HiddenValue
   {
        get
        {
             return hiddenValue;
        }
   }

   // Override ToString method
   public override string ToString()
   {
        return displayValue;
   }
}

然后在您的代码中:

// Add item to ComboBox:
ComboBox.Items.Add(new ComboBoxItem("DisplayValue", "HiddenValue");

// Get hidden value of selected item:
string hValue = ((ComboBoxItem)ComboBox.SelectedItem).HiddenValue;

这篇关于带有组合框项目的隐藏 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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