2013-02-22 18 views
1

我有2個使用相同BindingSource的文本框。當我更新一個文本框並失去焦點時,另一個文本框不會將其屬性更新爲新值。當我更改2個綁定文本框中的一個時,相同的DataBinding不更新

任何幫助將不勝感激。

using System.Data; 
    using System.Windows.Forms; 
    using System.ComponentModel; 

    namespace TextBoxes 
    { 
     public partial class Form1 : Form 
     { 
      BindingSource bs1 = new BindingSource(); 
      public Form1() 
      { 
       InitializeComponent(); 
       this.Load += Form1_Load; 
      } 
      void Form1_Load(object sender, System.EventArgs e) 
      { 
       DataTable dt = new DataTable(); 
       dt.Columns.Add("Name"); 
       dt.Rows.Add("Donald Trump"); 
       dt.Rows.Add("Sergei Rachmaninoff"); 
       dt.Rows.Add("Bill Gates"); 

       bs1.DataSource = dt; 
       bs1.RaiseListChangedEvents = true; 
       bs1.CurrencyManager.Position = 1; 

       textBox1.DataBindings.Add("Text", bs1, "Name"); 
       textBox2.DataBindings.Add("Text", bs1, "Name"); 
      } 
     } 
    } 

回答

0

你可以使用endEdit強制刷新 - 如果你把這個放在textchanged上,那麼當你改變textbox1時,textbox2會自動改變。

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    bs1.EndEdit(); 
} 

(並且如果您想要相互更新,請爲textbox2的textchanged做同樣的事情)。

雖然我會說如果你綁定到一個列表,會不會更好?

+0

感謝NDJ。我想用對話框編輯一個datagridview行。這是我的老闆想要的。 – Scott 2013-02-22 14:26:07

+0

您提供的解決方案對此問題最有意義。非常感謝! – Scott 2013-02-22 14:26:47

+0

不客氣!不能與老闆想要的東西爭論:) – NDJ 2013-02-22 14:27:21

0

添加下面的方法,在你的代碼...它會工作...

FormDesigner.cs

 this.textBox1.LostFocus += new System.EventHandler(this.textBox1_LostFocus); 
     this.textBox2.LostFocus += new System.EventHandler(this.textBox2_LostFocus); 

Form.cs

 private void textBox1_LostFocus(object sender, EventArgs e) 
     { 
      textBox2.DataBindings.Clear(); 
      textBox2.DataBindings.Add("Text", bs1, "Name"); 
     } 

     private void textBox2_LostFocus(object sender, EventArgs e) 
     { 
      textBox1.DataBindings.Clear(); 
      textBox1.DataBindings.Add("Text", bs1, "Name"); 
     } 
+0

謝謝潘丹! – Scott 2013-02-22 14:21:30

+0

@Scott:歡迎:) – Pandian 2013-02-22 14:22:14

相關問題