Eric after dark
Eric after dark

Reputation: 1808

How do I highlight the text in a textbox at the startup of a window?

I asked a question similar to this a few days ago here. The answer works fine, with the exception of performing the same operation at the start up of the window. This means that I need to have the text in a textBox highlighted every time the window is opened.

Currently I am setting the focus to the textBox at startup with no problem in the constructor. With that being said, I am guessing that the correct area to perform this operation is in the constructor. This is what I am trying currently with no luck:

public AddDestination()
{
     InitializeComponent();

     //Give cursor focus to the textbox
     destination_textBox.Focus();

     //Highlights text **DOES NOT WORK
     destination_textBox.SelectionStart = 0;
     destination_textBox.SelectionLength = destination_textBox.Text.Length;
}

How can I make it so that the text inside my textBox is highlighted whenever the window opens?

Upvotes: 0

Views: 102

Answers (2)

Adrian
Adrian

Reputation: 713

You can write this segment of code in Load EventHandler

//code
InitializeComponent();
//code

private void Form_Load(object sender, EventArgs e)
{
     //Give cursor focus to the textbox
     destination_textBox.Focus();

     //Highlights text **DOES NOT WORK
     destination_textBox.SelectionStart = 0;
     destination_textBox.SelectionLength = destination_textBox.Text.Length;
}

To do so go to Designer, click on the window, go to Properties, click Events button, search for Load event then double-click on it.

Upvotes: 1

Dmitri E
Dmitri E

Reputation: 253

Instead of constructor, move it to AddDestination_Load event.

     public AddDestination()
    {
        InitializeComponent();
    }

    private void AddDestination_Load(object sender, EventArgs e)
    {
        //Give cursor focus to the textbox
        textBox1.Focus();

        //Highlights text **DOES NOT WORK
        textBox1.SelectionStart = 0;
        textBox1.SelectionLength = textBox1.Text.Length;

    }

Upvotes: 1

Related Questions