Kelly Cline Kelly Cline - 1 year ago 242
C# Question

Winforms Binding to ListBox

I have a Windows Form with a ListBox. The form has this method

public void SetBinding(BindingList<string> _messages)
{
BindingList<string> toBind = new BindingList<string>( _messages );
lbMessages.DataSource = toBind;
}


Elsewhere, I have a class called Manager that has this property

public BindingList<string> Messages { get; private set; }


and this line in its constructor

Messages = new BindingList<string>();


Finally, I have my startup program that instantiates the form and the manager and then calls

form.SetBinding(manager.Messages);


What else do I have to do so that a statement in Manager like this:

Messages.Add("blah blah blah...");


will cause a line to be added to and displayed immediately in the form's ListBox?

I don't at all have to do it this way. I just want my Manager class to be able to post to the form while it is doing its job.

Answer Source

I think the problem is with your SetBinding method where you are making a new binding list, which means you aren't binding to the list in the Manager object anymore.

Try just passing the current BindingList to the datasource:

public void SetBinding(BindingList<string> messages)
{
  // BindingList<string> toBind = new BindingList<string>(messages);
  lbMessages.DataSource = messages;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download