2013-04-08 72 views
0

Access 2003中,VS 2010的C#,Windows窗體應用程序文本框插入命令參數

我想是因爲我的文本框等的數據綁定到當前的數據我有這個問題,所以這個問題是我怎麼拿到後不清爽綁定源讀取新的數據,而不必關閉並重新啓動應用程序?沒有錯誤。我嘗試了很多方法,但是當應用程序正在運行時它們都不顯示新記錄,所以我做錯了什麼?

我的窗體加載看起來像這樣..

this.fnDisplayPosition(); 

bdSource = new BindingSource(); 
string sql = "SELECT * FROM Table1"; 
OleDbDataAdapter da = new OleDbDataAdapter(sql, myCon); 
DataSet ds = new DataSet(); 
da.Fill(ds, "Table1"); 

bdSource.DataSource = ds; 
// this.table1BindingSource.AddNew(); 
txtID.DataBindings.Add("Text", bdSource, "ID"); 
cBAG.DataBindings.Add("Text", bdSource, "AgeGroup"); 
cBGender.DataBindings.Add("Text", bdSource, "Gender"); 

的fnDisplayPosition方法讀取多少條記錄有其綁定到數據綁定...

this.label7.Text = this.table1BindingSource.Position + 1 + " of " + 
this.table1BindingSource.Count; 

作爲例子,這是我的導航按鈕..

this.table1BindingSource.MoveFirst(); 
this.fnDisplayPosition(); 

以下是我的插入方法,我可以添加新紀錄我從this網站上使用...

OleDbDataAdapter da = new OleDbDataAdapter(@"INSERT INTO Table1 (ID, AgeGroup, Gender)VALUES 
(@txtID, @cBAG, @cBGender", myCon); 

     string qry = @"select * from Table1"; 
     string upd = @"INSERT INTO Table1 (ID, AgeGroup, Gender) 
         VALUES(@txtID, @cBAG, @cBGender)"; 

myCon.Open(); 

     try 
     { 
      da.SelectCommand = new OleDbCommand(qry, myCon); 
      DataSet ds = new DataSet(); 
      da.Fill(ds, "Table1"); 

      DataTable dt = ds.Tables["Table1"]; 

      DataRow newRow = dt.NewRow(); 
      newRow["ID"] = txtID; 
      newRow["AgeGroup"] = cBAG; 
      newRow["Gender"] = cBGender; 
      dt.Rows.Add(newRow); 

      OleDbCommand cmd = new OleDbCommand(upd, myCon); 

      cmd.Parameters.AddWithValue("@ID", txtID.Text); 
      cmd.Parameters.AddWithValue("@AgeGroup", cBAG.Text); 
      cmd.Parameters.AddWithValue("@Gender", cBGender.Text); 

      da.InsertCommand = cmd; 
      da.Update(ds, "Table1"); 
      da.Fill(ds, upd); 
      } catch(Exception ex) { 
     Console.WriteLine("Error: " + ex); 
    } finally { 
     myCon.Close(); 
    } 
+0

要麼我的代碼是絕對垃圾或沒有人知道 – bucketblast 2013-04-09 09:37:40

回答

0

很多試錯後,我發現了什麼爲什麼發生。 tableadapters和綁定到其他文本框的綁定源的使用不是要走的路。你必須硬編碼。因此,要查看您的數據反映是否更新,刪除或添加新記錄而不關閉並重新聲明應用程序,則不能使用tableadapters或binding source。爲了清楚地理解我在說什麼,你是否這個網站,here。不管你使用什麼連接或你如何使用命令參數。無論如何,這只是我的看法。