簡體   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