chainerlt
chainerlt

Reputation: 267

C# Forms TextBox select text with caret position

I can't figure out if it is possible to programmatically select text in TextBox with also setting caret position? It always sets caret position to the end of selection:

Can I get caret at the beginning of selection? (any other place?)

Upvotes: 2

Views: 1762

Answers (2)

Lemonseed
Lemonseed

Reputation: 1732

It is indeed possible to accomplish this, however the text selection will only be visible when the TextBox control has focus.

The best way I can think of to implement for your particular application is to create a simple method as follows:

private void SetTextSelection(TextBox textBox, int start, int length)
{
    textBox.Select(start, length);
    textBox.Focus();
}

Then, with one line you can set the selection of the TextBox using a statement like the following:

SetTextSelection(textBox, 3, 4);

where textBox is the instance of your text box control, 3 is the zero-based starting index of the first character in the selection, and 4 is the length of the selection.

Positive lengths will select in the direction of left to right. Keep in mind that you can also specify negative lengths and the selection will go "backwards", in the same manner had you selected text with the mouse and dragged from right to left.

Upvotes: 1

Darshan Faldu
Darshan Faldu

Reputation: 1601

You need to use Select() method of TextBox

private void button1_Click(object sender, EventArgs e)
{
    textBox1.Focus();
    textBox1.Select(3, 4);
}

Note: Without focus of particular textbox select method does not work as intent. so you need to use focus method before select method.

Upvotes: 1

Related Questions