Stephen H. Anderson
Stephen H. Anderson

Reputation: 1068

Populate ListBox object from a list of custom objects

I have a list of Backup objects (a class I made) how can I bind the ListBox to my list of Backup objects so if I remove/modify/insert the list of backups then the ListBox is also updated automatically?

I've done this in C++(qt) by using models, however, I'm new to C# and can't find the solution.

Thanks

Upvotes: 2

Views: 915

Answers (1)

Charles May
Charles May

Reputation: 1763

Instead of using a List<t> use a BindingList<t>

Set your listbox's DataSource property to your BindingList instance
Set the listbox's DisplayMember to a property you want to see in the list

Items added/removed should update your listbox.

Here's an example with the DGV

BindingList<Employee> employees = new BindingList<Employee>();
private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {
            var emp = new Employee { FirstName = "fn" + i, LastName = "ln" + i, EmployeeId = i };
            employees.Add(emp);
        }
        dataGridView1.DataSource = employees;
    }
}class Employee
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

With this I get the following result in my DGV

enter image description here

Upvotes: 3

Related Questions