Search code examples
c#winformstextbox

How can I sync two TextBox control's Text properties?


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.


Solution

  • 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.