4

DataGridView当我点击一个按钮时,我需要动态添加行。我已经阅读了很多关于它的帖子,但所有这些帖子都有一个DataTableas DataSource。在我的情况下,DataSource是 aList并且行是自定义对象(产品)。请参阅以下代码:

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

但不起作用。

4

3 回答 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();
}
于 2013-01-10T13:52:02.147 回答
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; }
}
于 2013-01-10T14:15:25.713 回答
1

首先将产品添加到列表中,然后在 DataGridView 上调用 Refresh

于 2013-01-10T13:31:51.373 回答