elvispt
elvispt

Reputation: 4942

Control the position of the vertical scrollbars

I have a multi-line textbox (let's call it textBox1) that has plenty of text inside.

After doing a search, I highlight the string I was looking for with:

textBox1.SelectionStart = textBox1.Text.ToLower().IndexOf(STRING);  
textBox1.SelectionLength = STRING.Length;

Now when I call the form that contains the textbox it highlights the selected text, but what I would like to do is that the scrollbars would scroll automatically to the highlighted text.

I tried

textBox1.ScrollToCaret();  

But didn't work.

Any ideas?

Thank you.

Upvotes: 1

Views: 118

Answers (1)

Bob
Bob

Reputation: 99734

What event are you firing this from? The Form probably isn't in a state where it can process this. If you call from Form.Load it will be too soon. If you call from Form.Shown, it should work properly.

private void Form1_Shown(object sender, EventArgs e) {
    var STRING = "Suspendisse mi risus";

    textBox1.SelectionStart = textBox1.Text.IndexOf(STRING);
    textBox1.SelectionLength = STRING.Length;

    textBox1.ScrollToCaret();
}

Upvotes: 2

Related Questions