Pregunta

If I have two text boxes on a form, how can I make it so that their text properties are perfectly synced? Similar to what would happen if they both processed the same KeyDown event.

¿Fue útil?

Solución

I would do it this way:

        textBox1.TextChanged += (s, _) =>
        {
            if (!textBox2.Focused && textBox1.Text != textBox2.Text)
            {
                textBox2.Text = textBox1.Text;
            }
        };

        textBox2.TextChanged += (s, _) =>
        {
            if (!textBox1.Focused && textBox2.Text != textBox1.Text)
            {
                textBox1.Text = textBox2.Text;
            }
        };

Basically I'm responding to the TextChanged even on each text box, but making sure that the target text box doesn't have focus and that the text actually has changed. This prevents infinite back-and-forth loop trying to update the text and it makes sure that the current insertion point isn't changed by the text being overwritten.

Otros consejos

I would say that you partially answered your own question, have them both assigned to the same TextChanged EventHandler check which textbox has changed then update the Text property of the other one, something like this.

private void textBox_TextChanged(object sender, EventArgs e)
{
    if (((TextBox)sender).Equals(textBox1)) 
        textBox2.Text = ((TextBox)sender).Text;
    else
        textBox1.Text = ((TextBox)sender).Text;
}

Modified Code to Keep Carat Position Synced between the two TextBox's , see if this is what you are wanting.

private void textBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    if (tb.Equals(textBox1))
    {
        if (textBox2.Text != tb.Text)
        {
            textBox2.Text = tb.Text;
            textBox2.SelectionStart = tb.SelectionStart;
            textBox2.Focus();
        }
    }
    else
    {
        if (textBox1.Text != tb.Text)
        {
            textBox1.Text = tb.Text;
            textBox1.SelectionStart = tb.SelectionStart;
            textBox1.Focus();
        }
    }
}

I would simply do as follows:

bool flag1, flag2;

private void t1_TextChanged(object sender, EventArgs e)
{
    if (flag2) return;

    flag1 = true;
    t2.Text = t1.Text;
    flag1 = false;
}

private void t2_TextChanged(object sender, EventArgs e)
{
    if (flag1) return;

    flag2 = true;
    t1.Text = t2.Text;
    flag2 = false;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top