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