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

瘦欲@ 提交于 2020-01-01 04:16:10

问题


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?


回答1:


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 } } });
    }
}


来源:https://stackoverflow.com/questions/1565875/allowusertoaddrows-doesnt-work-with-with-list-datasource-on-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!