When you call txtBox.SelectAll()
in your code, all the text is selected. Than, when you type another character, the default (and expected) behavior is to overwrite the selection, so you end up only with the new character.
You can override this behavior with this code (see note below):
// Backup field for textBox1.Text
string _textBox1TextBkp = "";
private void textBox1_TextChanged(object sender, EventArgs e)
{
// Add the new characters to backup field
_textBox1TextBkp += textBox1.Text;
// If textBox1.Text is empty:
if(textBox1.Text == "")
{
if (_textBox1TextBkp.Length > 0)
{
// Option 1: Remove last character
_textBox1TextBkp = _textBox1TextBkp.Remove(_textBox1TextBkp.Length - 1);
// Option 2: Delete all text - clear backup field
//_textBox1TextBkp = "";
}
}
// Set textBox1.Text to the backup field if needed
if (_textBox1TextBkp != textBox1.Text)
{
// Remove TextChanged event before modifying the text.
// This avoid stack-overflow by triggering the event when still inside.
textBox1.TextChanged -= textBox1_TextChanged;
// Set textBox1.Text to the backup field
textBox1.Text = _textBox1TextBkp;
// Add the removed event
textBox1.TextChanged += textBox1_TextChanged;
}
// Call SelectAll
textBox1.SelectAll();
}
when deleted a character (Backspace), you have two options in this code:
Option 1: Remove last character.
Option 2: Delete all text.
Note: the code assumes that when deleted a character (Backspace), all text is selected and the text-box is cleared. If all text is not selected, its more complicated and I did not deal with that.