C# - DataGridView无法添加行?

11

我有一个简单的C# Windows窗体应用程序,应该显示一个DataGridView。作为数据绑定,我使用了一个对象(选择了一个名为Car的类),它看起来像这样:

class Car
{
    public string color { get; set ; }
    public int maxspeed { get; set; }

    public Car (string color, int maxspeed) {
        this.color = color;
        this.maxspeed = maxspeed;
    }
}

然而,当我将DataGridView属性AllowUserToAddRows设置为true时,仍然没有小*号使我可以添加行。

有人建议将carBindingSource.AllowAdd设为true,但是,当我这样做时,我得到了一个MissingMethodException,它说找不到我的构造函数。


我认为你需要一个无参构造函数(因为没有信息可传递给你的两个参数构造函数),那么你是如何绑定它的? - V4Vendetta
我不得不在我的绑定源上使用AllowNew。 - Kai Hartmann
3个回答

16

你的Car类需要有一个无参构造函数,数据源需要是类似于BindingList的东西。

将Car类更改为:

class Car
{
    public string color { get; set ; }
    public int maxspeed { get; set; }

    public Car() {
    }

    public Car (string color, int maxspeed) {
        this.color = color;
        this.maxspeed = maxspeed;
    }
}

然后绑定类似这样的东西:

BindingList<Car> carList = new BindingList<Car>();

dataGridView1.DataSource = carList;
你也可以使用BindingSource来实现此功能,但不是必须的。BindingSource提供了一些额外的功能,有时可能是必要的。
如果由于某种原因你绝对不能添加无参构造函数,则可以处理绑定源的添加新事件,并调用Car带参数的构造函数:
设置绑定:
BindingList<Car> carList = new BindingList<Car>();
BindingSource bs = new BindingSource();
bs.DataSource = carList;
bs.AddingNew +=
    new AddingNewEventHandler(bindingSource_AddingNew);

bs.AllowNew = true;
dataGridView1.DataSource = bs;

并且处理程序代码:

void bindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
    e.NewObject = new Car("",0);
}

1
BindingList解决了我的问题。 dataGridView1.DataSource = new BindingList<Car>(carList); - styfle

5
您需要添加AddingNew事件处理程序:
public partial class Form1 : Form
{
    private BindingSource carBindingSource = new BindingSource();



    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.DataSource = carBindingSource;

        this.carBindingSource.AddingNew +=
        new AddingNewEventHandler(carBindingSource_AddingNew);

        carBindingSource.AllowNew = true;



    }

    void carBindingSource_AddingNew(object sender, AddingNewEventArgs e)
    {
        e.NewObject = new Car();
    }
}

1
我最近发现,如果您使用 IBindingList 实现自己的绑定列表,则必须在您的 SupportsChangeNotification 中返回 true,除了 AllowNew
然而,DataGridView.AllowUserToAddRowsMSDN 文章仅指定以下备注:
如果 DataGridView 绑定到数据,则只有在此属性和数据源的 IBindingList.AllowNew 属性都设置为 true 时,用户才允许添加行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接