2016-04-27 69 views
1

假設我有兩個文本框,一個保存二進制數據,另一個保存ASCII碼。如果用戶讓我們說改變他們其中之一,我將如何在不需要按下按鈕的情況下同時更新其他文本框?C#同時更新兩個文本框?

+2

使用textchanged事件詳細檢查此鏈接https://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged(v=vs.110).aspx – rashfmnb

+1

看看textchange事件你需要小心,以確保你沒有發現自己在一個循環中改變一個COS另一個說它改變了,但它改變了COS你改變它 – BugFinder

+3

在兩個文本框中的'textchanged'將創建一個無限循環 –

回答

3

你必須防止無限循環asciiTextBox改變binaryTextBox.Text從而改變asciiTextBox.Text等),並且可以實現類似的東西:

private void asciiTextBox_TextChanged(object sender, EventArgs e) { 
    binaryTextBox.TextChanged -= binaryTextBox_TextChanged; 

    try { 
    binaryTextBox.Text = BinaryText(asciiTextBox.Text); 
    } 
    finally { 
    binaryTextBox.TextChanged += binaryTextBox_TextChanged; 
    } 
} 

private void binaryTextBox_TextChanged(object sender, EventArgs e) { 
    asciiTextBox.TextChanged -= asciiTextBox_TextChanged; 

    try { 
    asciiTextBox.Text = AsciiText(binaryTextBox.Text); 
    } 
    finally { 
    asciiTextBox.TextChanged += asciiTextBox_TextChanged; 
    } 
} 
+1

非常詳細的答案:) – rashfmnb

+0

嗯,我想我明白了。唯一我沒有得到的是binaryTextBox.TextChanged - = binaryTextBox_TextChanged;這條線發生了什麼?對不起,我是OOP的新手:p – Rafas

+1

當您使用兩個「TextBox」控件的「TextChanged」事件來同步它們的文本時,沒有無限循環。 'Text'屬性檢查,如果新值與之前的值相同,則不會引發'TextChanged'事件。 –

1

您正在使用TextChanged事件。當用戶在一個文本框中鍵入時,您在TextChanged處理程序中處理它。

,以避免無限循環,可以從TextChange事件在開始退訂,並在處理程序結束時再次訂閱:

private void TextChangedHandler(object sender, EventArgs e) 
{ 
    textbox1.TextChanged -= TextChangedHandler; 
    textbox2.TextChanged -= TextChangedHandler; 

    // set textbox values 

    textbox1.TextChanged += TextChangedHandler; 
    textbox2.TextChanged += TextChangedHandler; 

} 
+0

textchanged在這兩個文本框中將創建一個無限循環:我不是下來的選民 –

+0

我編輯了我的答案,謝謝@ un-lucky –

+0

@Roma當您使用兩個TextBox控件的TextChanged事件時沒有無限循環以同步它們的文本。 'Text'屬性檢查,如果新值與之前的值相同,則不會引發'TextChanged'事件。 –

1

使用TextChanged Event檢查這個link查看詳細

代碼

private void TextBox_TextChanged(object sender, EventArgs e) 
{ 
// update your target text bx over here 
} 

創建TextChanged Event只爲兩個一箱箱將 創造無限的循環

+0

當您使用兩個「TextBox」控件的「TextChanged」事件來同步它們的文本時,沒有無限循環。 'Text'屬性檢查,如果新值與之前的值相同,則不會引發'TextChanged'事件。 –

2

當然,您不需要取消註冊TextChanged事件並重新註冊!

當您使用兩個TextBox控件的TextChanged事件來同步它們的文本時,沒有無限循環。 Text屬性檢查,如果新值與以前的值相同,則不會引發TextChanged事件。

所以你不需要刪除處理程序。只需處理TextChanged事件並更新其他控件。

在下面的例子中,我有2 TextBox控制可以鍵入在兩個和反向串將被顯示在其它:使用上述圖案

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    this.textBox2.Text = new string(this.textBox1.Text.Reverse().ToArray()); 
} 

private void textBox2_TextChanged(object sender, EventArgs e) 
{ 
    this.textBox1.Text = new string(this.textBox2.Text.Reverse().ToArray()); 
} 

可以簡單地使用您的MakeBinaryMakeAscci方法。你應該只有可逆的方法。