【问题标题】:AllowUserToAddRows doesn't work with with List<> Datasource on DataGridViewAllowUserToAddRows 不适用于 DataGridView 上的 List<> 数据源
【发布时间】:2009-10-14 12:12:46
【问题描述】:
我有一个DataGridView,其中DataSource 设置为List<myClass>
但是,当我将AllowUserToAddRows 设置为true 时,新行指示器不显示,
当我将DataSource 设置为BindingList<myClass> 时,这似乎解决了问题。
问:应该将我的List<> 替换为BindingList<> 还是有更好的解决方案?
【问题讨论】:
标签:
c#
.net
winforms
datagridview
bindinglist
【解决方案1】:
myClass 有公共无参数构造函数吗?如果没有,您可以从 BindingList<T> 派生并覆盖 AddNewCore 以调用您的自定义构造函数。
(编辑)或者 - 只需将您的列表包装在 BindingSource 中,它可能会起作用:
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 } } });
}
}