1

In a Windows Forms App, I want to select all the text in a text box with txtBox.SelectAll() as the code for the text box but after I debug it I can only type ONE letter in the textbox that is selected. The letter keeps changing as I type. How do I write more than one letter that is selected?

    private void TextBox1_TextChanged(object sender, EventArgs e)
    {
        txtBox.SelectAll();
    }
  • 2
    You can't. Each time you type something it will get selected. Then when you type the next letter it will replace whatever is currently selected (the last letter you just typed). You need to rethink selecting everything in the TextChanged event. – Idle_Mind Jun 05 '19 at 17:47
  • 1
    As @Arias Adrian Purdel said, select all and then typing will replace what's selected. That's just how that functionality works. What are you trying to accomplish? Perhaps the solution to your challenge is not to use selectAll(). – PeonProgrammer Jun 05 '19 at 17:54

1 Answers1

0

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.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37