WinForms/C#:向Combox添加项目并控制Item值(数字)

Mar*_*tin 1 c# controls combobox winforms

我一直使用设计器将我的项目填充到一个combox中,所有我传递的都是一个字符串.

虽然现在我需要控制每个项目存储哪个键/索引.

我以为有一个项目对象,但我看了ADD的方法,它接受了对象..

我如何传递一个控件键/索引,即当我执行SelectedItem时返回的内容.

因此,如果我选择了text,我会返回一个显示在当前所选下拉列表中的字符串,但如果我选择了我想要获取一个我需要存储的自定义数字...

任何想法如何做到这一点?

提前致谢

Iai*_*ard 5

您需要将其绑定到key\value对象的集合,并使用DisplayMemberValueMember属性来设置显示/返回的内容.

下面是一个例子:

public class ComboItem
{
    public string stringValue { get; set; }
    public int indexValue { get; set; }
}

public void LoadCombo()
{
     List<ComboItem> list = new List<ComboItem>();
     // populate list...
     // then bind list
     myComboBox.DisplayMember = "stringValue";
     myComboBox.ValueMember = "indexValue";
     myComboBox.DataSource = list;
}
Run Code Online (Sandbox Code Playgroud)

然后

myComboBox.SelectedText       // will return stringValue
myComboBox.SelectedValue      // will return indexValue
myComboBox.SelectedItem       // will return the ComboItem itself
myComboBox.SelectedIndex      // will return the items index in the list
Run Code Online (Sandbox Code Playgroud)

或者你可以通过创建一个自定义组合项添加一个Tag属性(通常用于存储这样的东西)来存储索引,在这里读取如何执行此操作