问题
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