繁体   English   中英

C# - 向DataGridView添加新行

[英]C# - Add new row to a DataGridView

当我点击按钮时,我需要动态地向DataGridView添加行。 我已经阅读了很多关于它的帖子,但所有这些帖子都有一个DataTable作为DataSource 在我的例子中, DataSource是一个List ,行是自定义对象(Product)。 请参阅以下代码:

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

AllowUserToAddRow为true。 那么如何动态添加行?


据我了解,根据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();   
    }

但是不起作用。

您可以将列表包装在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();
}

使用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; }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM