themarshal
themarshal

Reputation: 1086

Trouble binding a BindingList to ListBox

In the app I'm working on, I need to maintain a list of Projects which are currently loaded, and display the names of each one in a ListBox (okay, multiple ListBoxes, but that's neither here nor there).

class Project
{
    public String Name;

    // Etc. etc...
}

I've got a BindingList object which contains all of the loaded Projects, and am binding it to my ListBox(es).

private BindingList<Project> project_list = new BindingList<Project>();
private ListBox project_listbox;

private void setList()
{
    project_listbox.DisplayMember = "Name";
    project_listbox.ValueMember = "Name";
    project_listbox.DataSource = project_list;
}

However when I do this, all that gets displayed in project_listbox is a set of the class names for the Project. Am I missing something here? Every reference that I could find regarding binding Lists to a ListBox uses a very similar setup.

Upvotes: 2

Views: 4937

Answers (3)

SubqueryCrunch
SubqueryCrunch

Reputation: 1495

A possible issue that one might have is that new items are not inserted to the BindingList but to its parent List

Upvotes: 0

CasperT
CasperT

Reputation: 3475

You need to make the properties readable :)

class Project
{
    public string Name {get; private set;}

    // Etc. etc...
}

Now it should work. I just tested it.

This should work as well:

public readonly string Name;

As I have been pointed out. Putting "readonly" doesn't work. I just tested and verified it myself.

Upvotes: 4

splatto
splatto

Reputation: 3217

As an aside, note that if you want to search on or sort the BindingList, you will need to implement it and add this functionality

http://msdn.microsoft.com/en-us/library/ms993236.aspx

Upvotes: 0

Related Questions