WinForms/C#: Adding items to Combox and controlling the Item value (numeric)
I have been populating my Items to a combox using the designer and all i pass is a string.
Although now i need to control which key/index is stored with each item.
I thought th开发者_开发百科ere was a item object, but i looked at the method ADD and it accepts object..
How do i pass in an control the key/index i.e. what is returned when i do SelectedItem.
So if i do selectedtext i get back a string that is displayed in the current selected dropdown but if i do selecteditem i want to get back a custom number that i need to store with it...
Any ideas how to do this?
Thanks in advance
You need to bind it to a collection of key\value objects and use the DisplayMember and ValueMember properties to set what is displayed/returned.
Heres an example:
public class ComboItem
{
public string stringValue { get; set; }
public int indexValue { get; set; }
}
public void LoadCombo()
{
List<ComboItem> list = new List<ComboItem>();
// populate list...
// then bind list
myComboBox.DisplayMember = "stringValue";
myComboBox.ValueMember = "indexValue";
myComboBox.DataSource = list;
}
Then
myComboBox.SelectedText // will return stringValue
myComboBox.SelectedValue // will return indexValue
myComboBox.SelectedItem // will return the ComboItem itself
myComboBox.SelectedIndex // will return the items index in the list
Alternatively you could store the index by adding a Tag property (which is often used to store things like this) by creating a custom combo item, have a read here for how to do this
精彩评论