C# - 向DataGridView添加新行

5

当我点击按钮时,我需要动态地向DataGridView添加行。我已经阅读了很多相关帖子,但是它们都使用DataTable作为DataSource。在我的情况下,DataSource是一个List,而行是自定义对象(Product)。请参见以下代码:

    List<Product> products = 
    (List<Product>)repository.Session.CreateCriteria<Product>().List<Product>();
    ProductsDataGrid.DataSource = products;

AllowUserToAddRow为真。那么我如何动态添加一行?


根据Nasmi Sabeer的回答,据我所理解,我已经尝试了:

    private void addProductBtn_Click(object sender, EventArgs e)
    {
        List<Product> products = (List<Product>) ProductsDataGrid.DataSource;
        products.Add(new Product());
        ProductsDataGrid.DataSource = products;
        ProductsDataGrid.Refresh();   
    }

但是它不起作用。
3个回答

5
您可以像这样将列表包装在BindingSource中:
BindingSource bs = new BindingSource();
bs.DataSource = products;

然后将网格的DataSource属性设置为bs

ProductsDataGrid.DataSource = bs;

然后将您的点击处理程序更新为

private void addProductBtn_Click(object sender, EventArgs e)
{
    ...
    bs.Add(new Product());
    ....
    ProductsDataGrid.Refresh();
}

1
这种方式不太易读,但效果很好。谢谢! =D 只是好奇,为什么简单的 List<Product> 不起作用呢? 顺便说一下,Refresh() 不是必要的。 - Cristhian Boujon
是的,这是一个好问题 :) 如果您查看 DataGridView 的 DataSource 属性的 MSDN 文档,它可以是实现 IList 接口的任何内容,其中包括 List<t>。我只能想到绑定到自定义类型时可能会出现一些内部绑定问题。文档继续说,首选的方法是通过 BindingSource 进行绑定,因为它会为您处理大多数绑定问题。 - prthrokz
@Overflow012 List不具备UI感知能力。您应该使用BindingListObservableCollection,具体取决于您是使用WinForms还是WPF。BindingSource是错误的做法。BindingSource用于非内存实现,例如通过OData。 - Aron

2

使用 BindingList

public partial class Form1 : Form
{
    private IBindingList blist;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Binding
        this.blist = new BindingList<Product>();
        this.dataGridView1.DataSource = this.blist;

    }

    private void button2_Click(object sender, EventArgs e)
    {
        // Add
        this.blist.Add(new Product { Id = 2, Text = "Prodotto 2" });
    }
}

public class Product
{
    public int Id { get; set; }

    public string Text { get; set; }
}

1
先将产品添加到列表中,然后在DataGridView上调用刷新。

它对我起作用了,你能更具体地说明你遇到的错误吗? - Nasmi Sabeer

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