【问题标题】:WinForms/C#: Adding items to Combox and controlling the Item value (numeric)WinForms/C#:向 Combox 添加项目并控制项目值(数字)
【发布时间】:2011-06-09 04:03:56
【问题描述】:

我一直在使用设计器将我的项目填充到组合框,我传递的只是一个字符串。

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

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

如何在控件中传递键/索引,即当我执行 SelectedItem 时返回的内容。

因此,如果我执行 selectedtext,我会返回一个显示在当前选定下拉列表中的字符串,但如果我执行 selecteditem,我想返回一个我需要存储的自定义数字...

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

提前致谢

【问题讨论】:

标签: c# winforms controls combobox


【解决方案1】:

您需要将它绑定到键\值对象的集合,并使用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;
}

然后

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

或者,您可以通过创建自定义组合项have a read here for how to do this 来添加Tag 属性(通常用于存储此类内容)来存储索引

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多