2017-03-04 62 views
0

我用下面的方法來建立數據源:如何在C#中的Datagridview中添加新行?

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; 
+0

添加Person'類的'另一個實例'人列表並重新綁定。這是Windows窗體應用程序? – Nino

+0

你能看到我的更新嗎? – SFSFSFSF

+0

是的,我可以。薄winForms應用程序?在哪個事件中你填充DataGridView? – Nino

回答

0

我假設你正在使用的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; 
    } 

} 
+0

它可以工作,但會刪除所有行並添加新行後。但我需要添加新行到存在的行 – SFSFSFSF

+0

從哪裏得到:'dataGridView1.DataSource = people;'? – SFSFSFSF

+0

確保你只需要初始化加載一次(這個代碼塊我已經放在Form_Load中) – Nino

相關問題