AllowUserToAddRows doesn't work with with List<> Datasource on DataGridView

Wahid Bitar picture Wahid Bitar · Oct 14, 2009 · Viewed 10.3k times · Source

I have a DataGridView with the DataSource set to List<myClass>

However, the new row indicator does not display when I set AllowUserToAddRows to true,

When I set the DataSource to BindingList<myClass>, that seems to solve the problem.

Q: Should replace my List<> with BindingList<> or there is better solution?

Answer

Marc Gravell picture Marc Gravell · Oct 14, 2009

Does myClass have a public parameterless constructor? If not, you could derive from BindingList<T> and override AddNewCore to call your custom constructor.

(edit) Alternatively - just wrap your list in a BindingSource and it may work:

using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class Person {
    public string Name { get; set; }

    [STAThread]
    static void Main() {
        var people = new List<Person> { new Person { Name = "Fred" } };
        BindingSource bs = new BindingSource();
        bs.DataSource = people;

        Application.Run(new Form { Controls = { new DataGridView {
            Dock = DockStyle.Fill, DataSource = bs } } });
    }
}