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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With