[2.0] Binding a list to listbox
Is there a way to Bind a list (or bindinglist) of structs to a listbox?
When I set my datasource, I get "WindowsTestingGrounds.scData"
I am unable to alter the .DisplayMember prop of the listBox to be anything relevant.
Here is a simple example.
I'd like to see a list of all the first names.
Code:
namespace WindowsTestingGrounds
{
public partial class FormBindList : Form
{
public FormBindList()
{InitializeComponent();}
BindingList<scData> scdataList = new BindingList<scData>();
private void button1_Click(object sender, EventArgs e)
{
scdataList.Clear();
scdataList.Add(new scData("Roger", "Moore"));
scdataList.Add(new scData("Pierce", "Bronsen"));
scdataList.Add(new scData("Sean", "Connery"));
listBox1.DataSource = scdataList;
listBox1.DisplayMember = "scData.fname";
}
}
struct scData
{
string fname;
string lname;
public scData(string F, string L)
{
fname = F;
lname = L;
}
}
}
Re: [2.0] Binding a list to listbox
The problem is you are assigning the wrong DisplayMember. Use "key" instead since you are using a key/value pair type object. DisplayMember is which field to display. UseValue, not sure if a ListBox has this one, is which field to use as the value.
Re: [2.0] Binding a list to listbox
Your problem is actually your structure declaration. You certainly can bind a list of structure instances to a ListBox but data binding only supports properties, not fields. You cannot bind your ListBox to the 'fname' and 'lname' fields. You must make the fields private and expose them via public properties. You can then bind to those properties.