The listbox item collection can be any type of object, including String, and by default will display the result of obj.ToString();
Now the clever thing is that if a collection is bound via the listbox's DataSource property then the listbox display and the listbox value can be different. The display is governed by the DisplayMember property and the value (returned by SelectedValue) by the ValueMember property.
1) Define a simple class containing two string properties, one for display and one for value.
public sealed class ListBoxItem {
private String displayField;
private String valueField;
public ListBoxItem(String displayString, String valueString) {
DisplayString = displayString;
ValueString = valueString;
}
public String DisplayString {
get { return displayField; }
set { displayField = value; }
}
public String ValueString {
get { return valueField; }
set { valueField = value; }
}
}
2) Setup the listbox with a collection of ListBoxItem objects as the DataSource
private void SetupListBox() {
List<ListBoxItem> myItems = new List<ListBoxItem>();
myItems.Add(new ListBoxItem("qwerty COMX..COMY", "COM2"));
myItems.Add(new ListBoxItem("Unreliable COM adapter", "COM5"));
myItems.Add(new ListBoxItem("Onboard COM", "COM1"));
lbx.DisplayMember = "DisplayString";
lbx.ValueMember = "ValueString";
lbx.DataSource = myItems;
lbx.SelectedValueChanged += new EventHandler(SelectedValueChanged);
LoadSettings();
}
private void LoadSettings() {
lbx.SelectedValue = "COM1";
}
private void SelectedValueChanged(object sender, EventArgs e) {
if (lbx.SelectedValue != null) {
Debug.Print("Selected port is {0}", lbx.SelectedValue);
} else {
Debug.Print("Null - nothing selected");
}
}
It's a bit of work to setup but gives complete separation of display and value. If SelectedValue is assigned a value which is not in the collection then the highlight is removed and SelectedValue will return null.
Alan.