Question

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?

Was it helpful?

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;
}

OTHER TIPS

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

This assumes that the other TextBox is named textBox2 and that the first is named textBox1.

If you're working in WPF/XAML, you can use binding.

In your XAML:

<TextBox x:Name="textBox1" />
<TextBox Text="{Binding ElementName=textBox1, Path=Text}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top