How to Insert Text at Cursor Location

TechGnome

Well-known member
Joined
May 23, 2005
Messages
896
Programming Experience
10+
This had been my reply to another thread, but it got locked while I was composing. I'm posting it here, removing the now non-relevant stuff in the hopes that it may help someone else.

There are three properties that are used:
* SelectionStart
* SelectedText
* SelectionLength

First up, SelectionStart and SelectedText.
.SelectionStart will give your the character position where the cursor is currently located.
.SelectedText will insert any text you assign to it at the position were .SelectionStart is.

Example:
Assume a textbox called Text1 and it has the text 123456 in it.
VB.NET:
Text1.SelectionStart = 3
Text1.SelectedText = "Hello World!"
Text1 will now contain 123HelloWorld!456

Now, there's a danger, depending on how you want to look at it.
.SelectionLength will tell you how many characeters have been selected.
.SelectedText will then return that text. Setting it will OVERWRITE any selected text.

Example:
VB.NET:
Text1.SelectionStart = 3
Text1.SelectionLength = 3
Text1.SelectedText = "Hello World!"
Result is that Text1 will now contain "123Hello World!"

I would also like to add, that while I manualy selected the text to replace, SelectedText, SelectionStart and SelectionLength can also be read to see if the user has selected some text.

VB.NET:
MsgBox "You selected the text: " & Text1.SelectedText

Tg
 
Back
Top