开发者

Set both Text and Value property of ComboBox in design time

I need to add the following items to a combo box.

Value DisplayText

Mpost Posted

Call Calling

RScan Re-Scan

These items are fairly static, and is not retrieved from any database... Hence thought of assigning these in design time itself.

I'm Unable to use Items property as it asks only one value per item... Could you please help.

Ps : In case you are suggesting Bindin开发者_开发技巧gSource, could you please give me an example. I was not able to find one.


You could use a BindingList<KeyValuePair<string, string>>:

var items = new BindingList<KeyValuePair<string, string>>();

items.Add(new KeyValuePair<string, string>("Mpost", "Posted"));
items.Add(new KeyValuePair<string, string>("Call", "Calling"));
items.Add(new KeyValuePair<string, string>("RScan", "Re-Scan"));

myComboBox.DataSource = items;
myComboBox.ValueMember = "Key";
myComboBox.DisplayMember = "Value";

I don't think you're going to find a solution much simpler or more straightforward than this. Just put that in your form's constructor (after InitializeComponent--and by the way, I'd attach any event handlers you intend to add to the ComboBox after this point in the code) and you're good.

As for why there isn't an even easier way: honestly, I'd say this is a typical example of how solutions become more complex the more flexible you try to make them. Don't get me wrong; the ComboBox is quite a nice little control. But the thing is, it's designed to take any legitimate backing source, not just a table, or a list, or a collection of items with exactly two properties. Since it can take any data source, the concept of a strict key/value pairing is somewhat stripped of its special status. So it wouldn't make much sense to provide some special GUI for adding items with exactly two properties (though it might be convenient in this particular situation).


private class Data
{
    public string Name { get; set; }
    public string Value { get; set; }
}
public Form1()
{
    InitializeComponent();
    comboBox1.Items.Add(new Data{Name = "Test", Value = "Hello"});
    comboBox1.Items.Add(new Data {Name = "Test2", Value = "World"});
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Value";
}

You define the property to be used for display as DisplayMember and the property to be used for the value as ValueMember.

greetings Daniel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜