簡體   English   中英

如何在C#中的Datagridview中添加新行?

[英]How to add new row in Datagridview in C#?

我使用以下方法來構建數據源:

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;

如何在此GridView中添加新行?

我試過了,但它會重新加載所有數據:

 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;

我假設您正在使用WinForms應用程序...

首先,將BindingList<Person> people = new BindingList<Person>(); 聲明在您的類范圍內,以便在所有方法中都可見。 然后,假設您在FormLoad事件中填充DataGridView,並在button1_Click上添加其他事件:

因此,應該這樣進行:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM