Search code examples
c#datagridviewrowadditionwindows-forms-designer

System.InvalidOperationException: rows cannot be programmatically added to the datagridview's rows collection when the control is data-bound


I have a datagridview which I fill with a txt file which have 7 columns and 20 rows by default.

I want to add new rows to my datagridview using a button and textboxes in two different form, form1 for open form2 which contains the textboxes and the "ADD" button.

But I always got an error:

System.InvalidOperationException: rows cannot be programmatically added to the datagridview's rows collection when the control is data bound

What can I do?

I have tried

form1.datagridview.add(textbox1.text,textbox2.text...etc.) 

but it's not working.


Solution

  • If you are using data binding to bind your values to the DataGridView, instead of adding the row to the control itself you will have to add the new value to the actual list that the DataGridView is bound to.

    There is only one problem with that: Just adding the value to the data source will not refresh the DataGridView so you will not see it in the UI.

    So what you actually want to do is using a BindingSource. The BindingSource is bound to the DataGridView.DataSource and also has a DataSource-Property itself wich is your actual list of values.

    Here is a small example:

    public partial class Form1 : Form
    {
        private BindingSource _dataSource;
    
        public Form1()
        {
            InitializeComponent();
                
            _dataSource = new BindingSource();
            _dataSource.DataSource = new List<Person>
            {
                new Person { Name = "User1", Age = 1 },
                new Person { Name = "User2", Age = 2 },
            };
    
            dataGridView1.DataSource = _dataSource;
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            _dataSource.Add(new Person { Name = "User3", Age = 3 });
        }
    }
    
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    

    (dataGridView1 was created by dragging-and-dropping it from the toolbox to the form so the properties all have default values)

    I used this question as a reference for this answer: How can I refresh c# dataGridView after update ?