I have a listbox and a ListItem object which I am adding to the listbox so that I can retrieve a value from the selected item which is different then the displayed member.
try this it should work for you!
class ListItem
{
public string DisplayMember;
public string ValueMember;
public ListItem(string n,string v){
DisplayMember = n;
ValueMember = v;
}
}
public CompareTimeFramesForm()
{
InitializeComponent();
listBox1.Items.Add(new ListItem("# of Bookings", null).DisplayMember);
listBox1.Items.Add(new ListItem("People", "guaranteed_count").DisplayMember);
}
From MSDN:
When an object is being added to the ListBox, the control uses the text defined in the ToString method of the object unless a member name within the object is specified in the DisplayMember property.
ListBox
will convert item to string calling ToString()
. In your case you just need to change your ListItem
class like this:
class ListItem
{
public string DisplayMember;
public string ValueMember;
public ListItem(string n,string v) {
DisplayMember = n;
ValueMember = v;
}
public override string ToString() {
return DisplayMember;
}
}
As alternative you can se the DisplayMember
property (in designer or with code) to use your property (you called that property DisplayMember
but its name is free because it must be specified and it doesn't use any convention):
listBox1.DisplayMember = "DisplayMember";