|
-
Mar 6th, 2007, 09:42 AM
#1
Thread Starter
Fanatic Member
[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;
}
}
}
-
Mar 6th, 2007, 10:30 AM
#2
Hyperactive Member
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.
Currently Using: VS 2005 Professional
-
Mar 6th, 2007, 05:42 PM
#3
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|