UnyMath
UnyMath

Reputation: 49

C# Insert char at cursor position in textbox

I know there are some answers on stackoverflow but when I try it it inserts the text at the begin of text...

I tried

string insertText = "$";
int selectionIndex = textBox1.SelectionStart;
textBox1.Text = textBox1.Text.Insert( selectionIndex, insertText );

Upvotes: 1

Views: 2203

Answers (1)

adjan
adjan

Reputation: 13652

I don't know exactly in what context you are using it, but for me (.NET 4.6.1) this code works fine if used in a button handler, but only after the first click. Changing the text in the TextBox seems to reset the cursor position.

So to keep the cursor at its original place you have to set it back to what it was before you inserted the new text:

string insertText = "$";
int selectionIndex = textBox1.SelectionStart;
textBox1.Text = textBox1.Text.Insert( selectionIndex, insertText );
textBox1.SelectionStart = selectionIndex; // restore cursor position

Upvotes: 3

Related Questions