Reputation: 20906
I have comboBox component and i am adding items like comboBox1.Items.Add("Item1")
. But i alo need to know some other info about this Item. So if i click "Item1" i need to get "102454"
.
Can i somehow save 102454 to "Item1" on combobox.
At web aplication there is dropdown list which look like
<select>
<option value="102454">Item1</option>
</select>
and when i click "Item1" i get 102454
.
Can i do this in windows desktop applicatin with combobox?
Upvotes: 1
Views: 1227
Reputation: 10064
Edit better solution:
Use a KeyValuePair
and ValueMember
\ DisplayValue
:
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";
comboBox1.Items.Add(new KeyValuePair<int, string>(102454, "Item1"));
As Kristian points out this can be extended to be even more flexible - you can put whatever object you like into the list of items, and set the value and display members on the combobox to be whatever property path you want.
To get the key back later you can do this:
var item = combobox1.SelectedItem;
int key = ((KeyValuePair<int, string>)item).Key;
Upvotes: 3
Reputation: 56934
A have created a similar class like Mark Pim suggested; however, mine uses generics. I certainly would not choose to make the Value property a string type.
public class ListItem<TKey> : IComparable<ListItem<TKey>>
{
/// <summary>
/// Gets or sets the data that is associated with this ListItem instance.
/// </summary>
public TKey Key
{
get;
set;
}
/// <summary>
/// Gets or sets the description that must be shown for this ListItem.
/// </summary>
public string Description
{
get;
set;
}
/// <summary>
/// Initializes a new instance of the ListItem class
/// </summary>
/// <param name="key"></param>
/// <param name="description"></param>
public ListItem( TKey key, string description )
{
this.Key = key;
this.Description = description;
}
public int CompareTo( ListItem<TKey> other )
{
return Comparer<String>.Default.Compare (Description, other.Description);
}
public override string ToString()
{
return this.Description;
}
}
It is also easy to create a non-generic variant of it:
public class ListItem : ListItem<object>
{
/// <summary>
/// Initializes a new instance of the <see cref="ListItem"/> class.
/// </summary>
/// <param name="key"></param>
/// <param name="description"></param>
public ListItem( object key, string description )
: base (key, description)
{
}
}
Upvotes: 0