簡體   English   中英

C#同時更新兩個文本框?

[英]C# update two text boxes at the same time?

假設我有兩個文本框,一個文本框保存二進制數據,另一個文本框等效於ASCII。 如果用戶說更改其中任何一個,那么我如何在不按下按鈕的情況下同時更新另一個文本框?

您必須防止無限循環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;
  }
}

當然,您不需要注銷TextChanged事件並重新注冊!

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

因此,您無需刪除處理程序。 只需處理TextChanged事件並更新其他控件。

在下面的示例中,我有2個TextBox控件,您都可以鍵入兩個控件,並且反向字符串將顯示在另一個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方法。 您只能使用可逆方法。

您應該使用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;

}

使用TextChanged Event檢查此鏈接以獲取詳細信息

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

僅為一個框創建TextChanged Event ,兩個框都將創建無限循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM