2012-02-08 83 views
1

我有一個窗體上有多個文本框和一個數據表,數據表綁定到文本框,我正在處理數據表的RowChanged事件。文本框綁定更新事件

然而,當加載形式RowChanged事件只調用兩次(有超過兩個文本框),將數據從數據表中加載罰款到文本框,但是當我改變文本框的文本沒有任何事件觸發。然而,直接從數據表中顯示數據顯示數據已更新。

代碼:

private Clients.DataSetClients.ClientsDataTable dtClients = new DataSetClients.ClientsDataTable(); 
private Clients.DataSetClientsTableAdapters.ClientsTableAdapter taClients = new DataSetClientsTableAdapters.ClientsTableAdapter(); 

    private void ClientsEdit_Load(object sender, EventArgs e) 
    { 
     dtClients.RowChanged += new DataRowChangeEventHandler(dtClients_RowChanged); 

     taClients.FillByID(dtClients, ClientID); 

     textForename.DataBindings.Add("Text", dtClients, "Forename", true, DataSourceUpdateMode.OnPropertyChanged); 
     //....... 
     // etc 
     //....... 
     textEmail.DataBindings.Add("Text", dtClients, "Email", true, DataSourceUpdateMode.OnPropertyChanged); 
    } 

    void dtClients_RowChanged(object sender, DataRowChangeEventArgs e) 
    { 
     MessageBox.Show("dtClients_RowChanged"); 
    } 

    private void simpleButton1_Click(object sender, EventArgs e) 
    { 
     MessageBox.Show(dtClients.Rows[0]["Email"].ToString()); 
    } 

回答

1

你可以嘗試連線了BindingComplete事件,而不是綁定的DataTable中的RowChanged事件(這是更添加的行和列位置的變化等)。

private void ClientsEdit_Load(object sender, EventArgs e) 
{ 
    // loading stuff 
    Binding ForenameBinding = new Binding("Text", dtClients, "Forename", true, DataSourceUpdateMode.OnPropertyChanged); 
    ForenameBinding.BindingComplete += Table_BindingComplete; 
    textForename.DataBindings.Add(ForenameBinding); 
    // loading stuff 
} 

void Table_BindingComplete(object sender, BindingCompleteEventArgs e) { 
    if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate) 
    MessageBox.Show("Source Updated!"); 
} 

每次用戶更改文本框中的文本時,都會彈出該MessageBox,因此它會在每個關鍵筆劃上觸發。爲了避免這種情況,改變你的綁定模式OnValidation

Binding ForenameBinding = new Binding("Text", dtClients, "Forename", true, DataSourceUpdateMode.OnValidation); 
+0

我剛剛嘗試完全相同的事情,但使用綁定的.Format事件。我將使用.BindingComplete,因爲它似乎更適合。謝謝您的幫助! – baked 2012-02-08 15:06:33

0
private void button1_Click(object sender, EventArgs e) 
     { 
      List<string> names=new List<string>(){"Forename","Email","Phone"}; 
      foreach (var name in names) 
      { 
       var txt = this.Controls["text" + name] as TextBox; 
       txt.DataBindings.Add("Text", dtClients, name, true, DataSourceUpdateMode.OnPropertyChanged); 
      } 

     } 
+0

所有這樣做是將DataTable綁定到文本框,我已經做了。問題是dataTable.RowChanged事件在我期望的時候沒有被調用。 – baked 2012-02-08 09:11:03