2014-10-18 95 views
0

我第一次嘗試WinForms中的一些東西。我有一個問題,對我來說顯得非常微不足道,但後來我不是WinForms的人。搜索了很多,但找不到解決方案。DataGridView不在第二行後更新

下面是代碼,不用擔心內容本身,它只是測試代碼。問題是,當我點擊AddNew按鈕時,一行被添加到gridview,但之後沒有行被添加,無論用戶點擊AddNew按鈕多少次。你可以在下面的圖片中看到。

您可以指出爲什麼在添加行後沒有行被添加到gridview中。 AddNew按鈕僅適用於單擊。儘管它應該一次又一次地添加第二行。

在此先感謝。

public partial class JobCard : UserControl 
    { 
     List<Work> works = new List<Work>(); 
     BindingSource bs = new BindingSource(); 

     public JobCard() 
     { 
      InitializeComponent(); 

      works.Add(new Work() { S_No = 1, JobCategoryId = 1, JobCategoryName = "electricals", JobId = 1, JobName = "lights", Labour = 1, MaterialName = "tape", PartName = "headlight" }); 

      bs.DataSource = works; 
      dataGridView1.AutoGenerateColumns = true; 
      dataGridView1.DataSource = bs; 
     } 

     private void btnAddNew_Click(object sender, EventArgs e) 
     { 
      works.Add(new Work() { S_No = 2, JobCategoryId = 2, JobCategoryName = "electricals", JobId = 2, JobName = "lights", Labour = 2, MaterialName = "tape", PartName = "headlight" }); 
      dataGridView1.DataSource = works; 
     } 

    } 

Application snapshot

+0

我認爲問題出在你的按鈕代碼:dataGridView1.DataSource =工作。你應該重置綁定源。 – failedprogramming 2014-10-18 06:14:31

+0

該怎麼做? – tariq 2014-10-18 06:15:56

+0

嘗試:bs.DataSource = null; bs.DataSource =工程; – failedprogramming 2014-10-18 06:16:41

回答

1

您需要重置的BindingSource的數據源。

嘗試

private void btnAddNew_Click(object sender, EventArgs e) 
{ 
    ... 
    bs.DataSource = null; 
    bs.DataSource = works; 
}