Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Add new row to a DataGridView

I need to add dynamically rows to a DataGridView when I clicked on a button. I have read many posts about it but all of these have a DataTable as DataSource. In my case, the DataSource is a List and the rows are custom objects(Product). See the following code:

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

AllowUserToAddRow is true. So how can I add a row dynamically?


As I understand it, based on Nasmi Sabeer's answer I have tried:

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

But does not work.

like image 294
Cristhian Boujon Avatar asked Feb 18 '23 22:02

Cristhian Boujon


1 Answers

You can wrap your list around a BindingSource like so:

BindingSource bs = new BindingSource();
bs.DataSource = products;

And then set the DataSource property of the grid to bs.

ProductsDataGrid.DataSource = bs;

Then update your click handler as

private void addProductBtn_Click(object sender, EventArgs e)
{
    ...
    bs.Add(new Product());
    ....
    ProductsDataGrid.Refresh();
}
like image 130
prthrokz Avatar answered Feb 20 '23 12:02

prthrokz