Question How can I insert text into a textbox using a button (e.g. date)

12padams

Well-known member
Joined
Feb 19, 2010
Messages
48
Programming Experience
Beginner
Currently i have a button and a text box

I want to make it so i click the button and text gets added to the textbox the current carat location and then the carat is placed at the end of the selected text.

I currently have this in the button press event
VB.NET:
TextBox1.Text = TextBox1.Text.Insert(TextBox1.SelectionStart, "test")
which works except it deselects the text box and puts the carrot at the beginning of the text box

How can i put the carat just after where the text was inserted after pressing a button?

e.g. microsoft word insert data function
 
You can't, or at least not simply. What you're doing there is not just inserting a new bit of text into the existing text of the TextBox. That's how it may appear but that is not what's actually happening. You are first getting the String that the Text property contains. You are then calling its Insert method, which creates a new String object. You are then assigning that new String object to the Text property. That means that the TextBox now contains a completely new String, which has no relationship whatsoever to the old String it contained. The fact that they both contain similar text is of no consequence to the TextBox. As an analogy, two clocks showing the same time are not the same clock. Likewise, two Strings containing the same text are not the same String. They look the same, but they are not the same object.

So, what you're asking for is simply not possible. All you can do is determine the state of the TextBox before the change and then restore that state afterwards. It's simply not possible to get the scroll position exactly the same in many cases using simple managed code. You could probably resort to API calls or Windows messages but I wouldn't know exactly how.
 
I want to make it so i click the button and text gets added to the textbox the current carat location and then the carat is placed at the end of the selected text.
Take a note of SelectionStart value before you insert text, afterwards set SelectionStart to noted value + length of inserted text. You can then call ScrollToCaret method if needed.

The 'insert at caret position' functionality is actually 'replace selected text', so you normally use SelectedText for this, it work like an insert when SelectionLength is 0. The previous advice about retaining SelectionStart is still valid. If you also want to select the inserted text you can use the Select(start, length) method where start is the noted SelectionStart value and length is the length of the inserted text.
 
Back
Top