CodexBloom - Programming Q&A Platform

WinForms: Binding ComboBox to a List of Custom Objects - Getting 'Collection was modified' handling

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
winforms combobox binding exception C#

I'm not sure how to approach I'm working through a tutorial and I'm relatively new to this, so bear with me... Hey everyone, I'm running into an issue that's driving me crazy. Quick question that's been bugging me - I'm experiencing an scenario when trying to bind a ComboBox to a list of custom objects in my WinForms application. I have a simple form with a ComboBox and a Button. The ComboBox is supposed to display a list of `Product` objects that I retrieve from a service. However, when I modify the list (adding or removing items) and try to rebind it to the ComboBox, I encounter a `System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'` Here’s the code I’m using: ```csharp public class Product { public string Name { get; set; } public int Id { get; set; } } public partial class MainForm : Form { private List<Product> _products; public MainForm() { InitializeComponent(); LoadProducts(); comboBoxProducts.DisplayMember = "Name"; } private void LoadProducts() { _products = new List<Product> { new Product { Id = 1, Name = "Product 1" }, new Product { Id = 2, Name = "Product 2" } }; comboBoxProducts.DataSource = _products; } private void buttonAddProduct_Click(object sender, EventArgs e) { _products.Add(new Product { Id = 3, Name = "Product 3" }); RebindComboBox(); } private void RebindComboBox() { comboBoxProducts.DataSource = null; comboBoxProducts.DataSource = _products; } } ``` The behavior occurs when I click the button to add a product. I've tried setting the ComboBox's `DataSource` to null before re-binding, but it still throws the same exception. I suspect this might be due to the way the ComboBox is enumerating through the list when re-binding, but I can’t figure out how to solve this. I also considered using `BindingList<Product>` instead of `List<Product>`, but I want to understand why the exception happens in the first place. Any insights or suggestions would be greatly appreciated! My development environment is Windows. Is there a better approach? What am I doing wrong? I'm working on a CLI tool that needs to handle this. Any help would be greatly appreciated! I'm coming from a different tech stack and learning C#. This issue appeared after updating to C# LTS. Any examples would be super helpful.