Objects added to a BindingSource’s list must all be of the same type

By FoxLearn 12/21/2024 2:06:25 AM   8
When working with data binding in C#, one common scenario is binding a list of objects to a user interface control (like a DataGridView, ComboBox, or ListBox).

However, you may encounter an exception if you're not using the correct approach. Specifically, when binding a BindingList<T> to a BindingSource, you might see the following exception:

System.InvalidOperationException: Objects added to a BindingSource’s list must all be of the same type.

Resolving the "System.InvalidOperationException" in Data Binding with BindingList and BindingSource

This error typically occurs when attempting to add a BindingList<T> to a BindingSource incorrectly.

In this example, we will attempt to bind a list of employees to a BindingSource:

BindingList<Employee> employees = new BindingList<Employee>()
{
    new Employee() { Name = "John Doe", Department = "HR" },
    new Employee() { Name = "Jane Smith", Department = "IT" }
};

this.EmployeeCollectionBindingSource.Add(employees);  // Throws the exception

The issue here is that when you use the Add() method of the BindingSource, you're adding the entire BindingList<Employee> as a single item to the BindingSource. The BindingSource expects the individual items inside its list to be of the same type. In this case, you're adding a BindingList<Employee> (which is a collection of Employee objects) to the BindingSource, instead of directly adding the Employee objects themselves.

To resolve this issue, you need to set the DataSource property of the BindingSource to the BindingList<Employee>, rather than adding it with the Add() method. This will ensure that the BindingSource knows the BindingList<Employee> is its data source, and all items in the list will be treated as Employee objects.

BindingList<Employee> employees = new BindingList<Employee>()
{
    new Employee() { Name = "John Doe", Department = "HR" },
    new Employee() { Name = "Jane Smith", Department = "IT" }
};

this.EmployeeCollectionBindingSource.DataSource = employees;  // Correct approach

The key takeaway is that when binding a BindingList<T> to a BindingSource, you should set the DataSource property of the BindingSource to the BindingList<T>, rather than using the Add() method. This ensures that the BindingSource correctly understands that the data source consists of objects of the same type and avoids the System.InvalidOperationException.