Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

c# - ComboBox:向项添加文本和值(无绑定源)(ComboBox: Adding Text and Value to an Item (no Binding Source))

In C# WinApp, how can I add both Text and Value to the items of my ComboBox?

(在C#WinApp中,如何将Text和Value添加到我的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"
  ask by Bohn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must create your own class type and override the ToString() method to return the text you want.

(您必须创建自己的类类型并覆盖ToString()方法以返回所需的文本。)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...