Search code examples
c#stringtextboxpreview

C# Write in a TextBox and preview in another


I'd like to ask the following question: when I write in a TextBox, I want the text that I write to automatically be written to another TextBox (like a preview of what I write).

private void textBox1_TextChanged(object sender, EventArgs e)
{
    textBox2.Text = textBox1.Text
}

...But if the textBox2 contains text, the following code is a disaster:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    textBox2.Text += textBox1.Text
}

How can I insert and delete one letter at a time?


Solution

  • private void textBox1_TextChanged(object sender, EventArgs e)
    {
      textBox2.Text = textBox1.Text;
    }
    

    And yes textChanged is useful for this and exactly what you needed.

    Update:

    Define a variable for store your static text in textBox2:

    string staticText = textBox2.Text;
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
      textBox2.Text = staticText + textBox1.Text;
    }