组合框:添加文本和值到项目(不绑定源) [英] ComboBox: Adding Text and Value to an Item (no Binding Source)

查看:88
本文介绍了组合框:添加文本和值到项目(不绑定源)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#WinApp,我怎么能文本和值添加到我的ComboBox的项目?
我做了搜索,通常的答案是使用绑定到源..但在我来说,我没有绑定源准备在我的计划...
我怎样才能做这样的事情:

  combo1.Item [1] =DisplayText;
combo1.Item [1] .value的=使用价值


解决方案

您必须创建自己的类类型和重写ToString()方法返回你想要的文字。这里是一个类,你可以用一个简单的例子:

 公共类ComboboxItem
{
    公共字符串文本{搞定;组; }
    公共对象值{搞定;组; }    公共重写字符串的ToString()
    {
        返回文本;
    }
}

以下是其使用的一个简单的例子:

 私人无效测试()
{
    ComboboxItem项目=新ComboboxItem();
    item.Text =项目text1中;
    item.Value = 12;    comboBox1.Items.Add(项目);    comboBox1.SelectedIndex = 0;    MessageBox.Show((comboBox1.SelectedItem如ComboboxItem).Value.ToString());
}

In C# WinApp, how can I add both Text and Value to the items of my ComboBox? I did a search and usually the answers are using "Binding to a source".. but in my case I do not have a binding source ready in my program... How can I do something like this:

combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"

解决方案

You must create your own class type and override the ToString() method to return the text you want. Here is a simple example of a class you can use:

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

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

The following is a simple example of its usage:

private void Test()
{
    ComboboxItem item = new ComboboxItem();
    item.Text = "Item text1";
    item.Value = 12;

    comboBox1.Items.Add(item);

    comboBox1.SelectedIndex = 0;

    MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}

这篇关于组合框:添加文本和值到项目(不绑定源)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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