2017-09-24 99 views
0

美好的一天,通過BindingSource向DataGridView添加新條目

我正在寫一個PasswordManager,並且堅持向我的DataGridView添加新行。

你可以看到我的代碼在這裏:PassMangaer

發動機/ NewEntry.cs有創建一個新的條目並將其添加到BindingSource的代碼。 之後,PassManger/frmAddNewEntry.cs將其添加到主窗體上的DataGridView並刷新DataGridView。

實際上,它只是用新的行替換當前行,並沒有,因爲它應該添加一個新行。

我在這裏錯過了什麼?

回答

1

你的問題在frmAddNewEntry,第18行,當你創建BindingSource Bs = new BindingSource()。 btnAddEntry_Click適用於空Bs。 我的建議:

  1. PassManager。除去管線18
  2. 公共無效addNewEntry(BindingSource的BS,INT標識,串主控器)

  3. 私人無效btnAddEntry_Click(對象發件人,EventArgs的) { 串主控器= textBox1.Text; ne.addNewEntry(mainForm.Bs,1,hoster); mainForm.RefreshDGV(); this.Close(); }

不推薦使用,但一個將是你最後的評論快速燙:

 public void LoadData(DataGridView grid) 
    { 
     DataTable dataTable = new DataTable(); 
     foreach (DataGridViewColumn col in grid.Columns) 
     { 
      dataTable.Columns.Add(new DataColumn(col.Name)); 
     } 
     string file = "mygrid.bin"; 
     using (BinaryReader bw = new BinaryReader(File.Open(file, FileMode.Open))) 
     { 
      int n = bw.ReadInt32(); 
      int m = bw.ReadInt32(); 
      for (int i = 0; i < m; ++i) 
      { 
       dataTable.Rows.Add(); 
       for (int j = 0; j < n; ++j) 
       { 
        if (bw.ReadBoolean()) 
        { 
         dataTable.Rows[i][j] = bw.ReadString(); 
         dataTable.Rows[i][j] = Base64Decode(dataTable.Rows[i][j].ToString()); 
        } 
        else bw.ReadBoolean(); 
       } 
      } 
     } 
     grid.DataSource = dataTable; 
    } 
+0

謝謝您的回答,但如果我刪除18行,我怎麼傳實際的BindingSource? – Smarc

+0

好的,現在我有點困惑。我得到你的新功能,這對我來說很有意義。但現在我得到一個 System.NullReferenceException:'對象引用未設置爲對象的實例。' bs爲空。 in NewEntry.cs – Smarc

+0

在方法中使用mainForm.Bs作爲參數。告訴我你的addNewEntry,你怎麼稱呼它 –