C# - 向DataGridView添加新行

时间:2013-01-10 13:28:23

标签: c# datagridview

当我点击按钮时,我需要动态地将行添加到DataGridView。 我已经阅读了很多关于它的帖子,但所有这些帖子都有DataTable作为DataSource。就我而言,DataSourceList,行是自定义对象(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 个答案:

答案 0 :(得分:2)

您可以将列表包裹在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 :(得分: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; }
}

答案 2 :(得分:1)

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