Reputation: 886
I am doing a Windows Form Application and I have the following classes:
Person.cs
class Person
{
public string name{ get; set; }
public Person(string name)
{
this.name = name;
}
}
Repository.cs
class Repository
{
private static instance;
private Repository()
{
persons= new List<Person>();
}
public static Instance
{
get
{
if (instance == null)
{
instance = new Repository();
}
return instance;
}
}
private List<Person> videos;
public List<Person> getVideos()
{
return videos;
}
}
I want to bind a ListBox
in my Form
to the list of persons in my repository.
How can I do that? I am trying to do that using the designer, I have the field DataSource
in my ListBox
, do I bind it with my Person
or Repository
class? The fields of the cass must be public? After the binding any data I add to my repository will automatically appear in my ListBox
?
Upvotes: 0
Views: 1100
Reputation: 54453
Here is an absolutely minimal example of databinding a List<T>
to a ListBox
:
class Person
{
public string Name{ get; set; } // the property we need for binding
public Person(string name) { Name = name; } // a constructor for convenience
public override string ToString() { return Name; } // necessary to show in ListBox
}
class Repository
{
public List<Person> persons { get; set; }
public Repository() { persons = new List<Person>(); }
}
private void button1_Click(object sender, EventArgs e)
{
Repository rep = new Repository(); // set up the repository
rep.persons.Add(new Person("Tom Jones")); // add a value
listBox1.DataSource = rep.persons; // bind to a List<T>
}
Note: The display will not update on each change to the DataSource
for several reasons, most notably for performance. We can control the refresh, in a minimal way like this:
private void button2_Click(object sender, EventArgs e)
{
rep.persons.Add(new Person("Tom Riddle"));
listBox1.DataSource = null;
listBox1.DataSource = rep.persons;
}
Expanding the example a little, using a BindingSource
we can, among other things, call ResetBindings
to update the items shown like this:
private void button1_Click(object sender, EventArgs e)
{
rep.persons.Add(new Person("Tom Jones"));
rep.persons.Add(new Person("Tom Hanks"));
BindingSource bs = new BindingSource(rep, "persons");
listBox1.DataSource = bs;
}
private void button2_Click(object sender, EventArgs e)
{
rep.persons.Add(new Person("Tom Riddle"));
BindingSource bs = (BindingSource)listBox1.DataSource;
bs.ResetBindings(false);
}
Upvotes: 1