Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 690
Wahid Bitar Avatar asked Oct 14 '09 12:10

Wahid Bitar


Video Answer


1 Answers

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 } } });
    }
}
like image 178
Marc Gravell Avatar answered Sep 21 '22 14:09

Marc Gravell