0

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?

Community
  • 1
  • 1
Eric after dark
  • 1,768
  • 4
  • 31
  • 79

2 Answers2

1

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.

Adrian
  • 693
  • 5
  • 19
1

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;

    }
Dmitri E
  • 253
  • 1
  • 11