Search code examples
c#winformstextboxhighlight

How do I stop the text in a Winforms textbox from being automatically selected/highlighted when first displayed?


In the case where I don't want a user to inadvertently delete text displayed in a textbox when the textbox is first loaded and displayed, e.g., by inadvertently fumble-fingering on the keyboard, how do I stop the text in the textbox from being automatically selected when first displayed and before the user has access to it?


Solution

  • //set SelectionStart property to zero
    //This clears the selection and sets the cursor to the left of the 1st character in the textbox
    textBox1.SelectionStart = 0;
    
    //This clears the selection and sets the cursor to the end of whatever is in the textbox
    textBox1.SelectionStart = textBox1.Text.Length;