[英]How to add new row in Datagridview in C#?
I use following method to build datasource: 我使用以下方法来构建数据源:
BindingList<Person> people = new BindingList<Person>();
foreach (var tag in names)
{
people.Add(new Person
{
Id = tag.ID,
Name = tag.Name,
Tag = tag.Ref
});
}
dataGridView1.DataSource = people;
How to add a new row in this GridView? 如何在此GridView中添加新行?
I tried this, but it reloads all data: 我试过了,但它会重新加载所有数据:
BindingList<Person> people = new BindingList<Person>();
//set datagridview datasource
dataGridView1.DataSource = people;
//add new product, named Cookie, to list ant boom you'll see it in your datagridview
people.Add(new Person());
dataGridView1.DataSource = people;
I'll assume you're working with WinForms application... 我假设您正在使用WinForms应用程序...
First of all, put BindingList<Person> people = new BindingList<Person>();
首先,将
BindingList<Person> people = new BindingList<Person>();
declaration in scope of your class, so that it's visible in all methods. 声明在您的类范围内,以便在所有方法中都可见。 Then, lets assume you're populating DataGridView on
FormLoad
event, and adding other on button1_Click
: 然后,假设您在
FormLoad
事件中填充DataGridView,并在button1_Click
上添加其他事件:
So, that should be done like this: 因此,应该这样进行:
public partial class Form1 : Form
{
//declare new persons list here, not in method which loads data into list.
BindingList<Person> persons = new BindingList<Person>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//your initial loading is here, I guess
people = new BindingList<Person>();
foreach (var tag in names)
{
people.Add(new Person
{
Id = tag.ID,
Name = tag.Name,
Tag = tag.Ref
});
}
dataGridView1.DataSource = people;
}
private void button1_Click(object sender, EventArgs e)
{
Person p = new Person()
{
Id = 10,
Name = "NewPersonName",
Tag = 123
}
//you can see that I'm not making new instance of person list, just adding new Person inside
persons.Add(p);
dataGridView1.DataSource = people;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.