C#同时更新两个文本框?

时间:2016-04-27 14:00:36

标签: c# winforms user-interface

假设我有两个文本框,一个包含二进制数据,另一个包含ASCII等效文本框。如果用户让我们说改变其中一个,那么如何同时更新另一个文本框,而不必按一个按钮?

4 个答案:

答案 0 :(得分: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 :(得分:2)

当然,您不需要取消注册TextChanged事件并重新注册!

当您使用两个TextChanged控件的TextBox事件来同步它们的文本时,没有无限循环。 Text属性检查,如果新值与先前值相同,则不会引发TextChanged事件。

所以你不需要删除处理程序。只需处理TextChanged事件并更新其他控件。

在下面的示例中,我有两个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方法即可。你应该只有可逆的方法。

答案 2 :(得分:1)

你辱骂使用TextChanged事件。当用户在一个文本框中键入时,您可以在TextChange处理程序中处理它。

为避免无限循环,您可以在开头取消订阅private void TextChangedHandler(object sender, EventArgs e) { textbox1.TextChanged -= TextChangedHandler; textbox2.TextChanged -= TextChangedHandler; // set textbox values textbox1.TextChanged += TextChangedHandler; textbox2.TextChanged += TextChangedHandler; } 事件,并在处理程序结束时再次订阅:

when State=={Wait for Reply} && comments.added !=null 
    && comments.added.isNotEmpty && comments.added.last !=null 
    && !comments.added.last.author.isInGroup("Internal Developers"){

    State={Open};
}

答案 3 :(得分:1)

使用TextChanged Event查看此link了解详情

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

仅为两个框创建TextChanged Event   创造无限循环

相关问题