views:

491

answers:

2

Whenever I set focus to a Textbox in WinForms (.NET 3.5) the entire text is selected. Does not matter if I have MultiLine set to true or false. Seems to be the exact reverse of what this user is seeing: http://stackoverflow.com/questions/97459/automatically-select-all-text-on-focus-in-winforms-textbox

I have tried to do:

    private void Editor_Load(object sender, EventArgs e)
    {
       //form load event
       txtName.SelectedText = String.Empty; // has no effect
    }

Is there another property I can set to stop this annoying behavior?

I just noticed this works:

        txtName.Select(0,0);
        txtScript.Select(0,0);

But do I really need to call select() on all my textboxes?

A: 

Well, you won't need to use Focus() if you use Select(0,0), so I don't see the problem? It still ends up as a single call.

Kyle Rozendo
I think this is only happening to me because I'm setting the TextBox.Text value before the control is painted. Doesn't matter if I do it through Methods or Properties. No wonder I hadn't noticed this before.
tyndall
What form event could I tap into to make sure my textbox values are set after the form paint event?
tyndall
Ah I see. When are you setting the textboxes, in the constructor or in the loading event? If it is the constructor there's your problem.
Kyle Rozendo
I think it is just pre-Visible. I have tried it outside the constructor and outside of properties (methods). If I call the two methods before the form is visible (shown) it has this weird behavior. If I wait and call the two methods after, its fine. weird.
tyndall
In this case, try to initialize the textboxes in the Windows ContentRendered event. This event fires only once everything has been drawn, so in essence if the problem is what you think, it would solve the problem.
Kyle Rozendo
+1  A: 

Create a custom TextBox control that overrides the Enter event.

Something like this:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace YourNamespace  
{
    class MyTextBox : TextBox
    {

        protected override void OnEnter(EventArgs e) {
            this.Select(0, 0);

            base.OnEnter(e);
        }

    }
}
Jay Riggs
All good and well to do, but it doesn't solve the original problem.
Kyle Rozendo
As I read the question the problem is to prevent a number of TextBoxes from selecting all text when they're entered. My solution does solve this problem without a lot of hoop jumping. (It's true there could be something else in the OP's code that makes my solution unworkable, but I think it's worth considering).
Jay Riggs