c#ComboBox,保存带有值和文本的项目

时间:2014-01-29 16:08:24

标签: c# combobox

我正在尝试将带有TEXT和VALUE的对象ITEM添加到ComboBox中,以便稍后阅读

public partial class Form1 : Form
{
    ComboboxItem item;
    public Form1()
    {
        InitializeComponent();

        comboBox1.Items.Add(new ComboboxItem("Dormir", 12).Text);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ComboboxItem c = (ComboboxItem)comboBox1.SelectedItem;
        label1.Text = c.Text;
        label2.Text = c.Value.ToString();
    }
}

问题是,我无法添加完整的Item因为不是字符串...并在点击事件开始时给出例外


额外信息: 这个ComboboxItem,它是我用2个参数创建的类,字符串和int

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public ComboboxItem(string texto, double valor)
    {
        this.Text = texto;
        this.Value = valor;
    }
}

4 个答案:

答案 0 :(得分:0)

你不需要在(“text”,“value”)

的末尾添加.Text

所以将其添加为:

comboBox1.Items.Add(new ComboBoxItem("dormir","12"));

答案 1 :(得分:0)

通过创建自己的ComboBoxItem类,您就行了。

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

}

有两种方法可以使用它,(旁边的构造函数): 方法1:

private void button1_Click(object sender, EventArgs e)
{
    ComboboxItem item = new ComboboxItem();
    item.Text = "Item text1";
    item.Value = 12;

    comboBox1.Items.Add(item);
}

方法2:

private void button1_Click(object sender, EventArgs e)
{
    ComboboxItem item = new ComboboxItem 
    { 
         Text = "Item text1",
         Value = 12
    };

    comboBox1.Items.Add(item);
}

您是否尝试过这样添加?然后当你得到Item时,只需将它作为ComboboxItem投射:)

...
var selectedItem = comboBox1.SelectedItem as ComboboxItem;
var myValue = selectedItem.Value;
...

替代KeyValuePair:

comboBox1.Items.Add(new KeyValuePair("Item1", "Item1 Value"));

基于returnign字符串值和其他组合框答案的问题.. ComboBox: Adding Text and Value to an Item (no Binding Source)

答案 2 :(得分:0)

你可以(应该)在另一个地方设置displaymember和valuemember,但是......

public Form1()
    {
        InitializeComponent();
        comboBox1.DisplayMember="Text";
        comboBox1.ValueMember ="Value";
        comboBox1.Items.Add(new ComboboxItem("Dormir", 12));
    }

答案 3 :(得分:0)

创建ComboboxItem类并覆盖ToString方法。 将调用ToString方法以显示项目。默认情况下,ToString()返回类型名称。

public class ComboboxItem
{
   public object Value{get;set;}
   public string Text {get;set;}

   public override string ToString(){ return Text; }
}

然后,你可以这样做:

var item = new CombobxItem { Value = 123, Text = "Some text" };
combobox1.Items.Add(item);