I'm trying to create ListBox where I will have key-value pair. Those data I got from class which provides them from getters.
Class:
public class myClass
{
private int key;
private string value;
public myClass() { }
public int GetKey()
{
return this.key;
}
public int GetValue()
{
return this.value;
}
}
Program:
private List<myClass> myList;
public void Something()
{
myList = new myList<myClass>();
// code for fill myList
this.myListBox.DataSource = myList;
this.myListBox.DisplayMember = ??; // wanted something like myList.Items.GetValue()
this.myListBox.ValueMember = ??; // wanted something like myList.Items.GetKey()
this.myListBox.DataBind();
}
It's similar to this topic [ Cannot do key-value in listbox in C# ] but I need to use class that returns values from methods.
Is it possible to do somewhat simple or I'd better rework my thought flow (and this solution) completely?
Thank you for advice!
The DisplayMember
and ValueMember
properties require the name (as a string) of a property to be used. You can't use a method. So you have two options. Change you class to return properties or make a class derived from myClass where you could add the two missing properties
public class myClass2 : myClass
{
public myClass2() { }
public int MyKey
{
get{ return base.GetKey();}
set{ base.SetKey(value);}
}
public string MyValue
{
get{return base.GetValue();}
set{base.SetValue(value);}
}
}
Now that you have made these changes you could change your list with the new class (but fix the initialization)
// Here you declare a list of myClass elements
private List<myClass2> myList;
public void Something()
{
// Here you initialize a list of myClass elements
myList = new List<myClass2>();
// code for fill myList
myList.Add(new myClass2() {MyKey = 1, MyValue = "Test"});
myListBox.DataSource = myList;
myListBox.DisplayMember = "MyKey"; // Just set the correct name of the properties
myListBox.ValueMember = "MyValue";
this.myListBox.DataBind();
}