Inserting text into a textbox at the cursor position VB

Ben picture Ben · Jun 15, 2012 · Viewed 10.6k times · Source

I am trying to work out how I can insert the string "End" into my textbox at a specific cursor point? (where the '???' is in the code below)

As you can see by the code below this will happen when the user clicks return on the keyboard within the textbox.

I have the code to get the cursor index which is being stored as integer 'intcurrentcolumn'.

Thanks

 Private Sub Enter_Click(ByVal Sender As System.Object, ByVal k As System.Windows.Forms.KeyEventArgs)

     Dim MyTextBox As TextBox = sender
     Dim intindex As Integer
     Dim intcurrentcolumn As Integer
     Dim NewString As String

     If k.KeyCode = Keys.Return Then

        k.SuppressKeyPress = True

        intindex = MyTextBox.SelectionStart
        intcurrentColumn = intindex - MyTextBox.GetFirstCharIndexFromLine(intcurrentLine)

        If intindex = MyTextBox.Text.Length Then

         NewString = MyTextBox.Text & "<End>"

        Else: 

        ???

        End If

        MyTextBox.Text = NewString

        'Sets cursor to end of textbox
        MyTextBox.Select(MyTextBox.Text.Length, 0)

      End If

Thanks In Advance !

Answer

Konrad Rudolph picture Konrad Rudolph · Jun 15, 2012

The String.Insert method works but resets the cursor position which is generally not what you want (although your code resets it afterwards anyway). A better alternative is to just set the SelectedText:

MyTextBox.SelectedText = "<End>"

In your case, the selected text simply has length 0 before you insert the string "<End>".

This also makes the If…Else distinction unnecessary.

Private Sub Enter_Click(ByVal Sender As Object, ByVal k As System.Windows.Forms.KeyEventArgs)
    If k.KeyCode = Keys.Return Then
        Dim MyTextBox As TextBox = DirectCast(sender, TextBox)
        MyTextBox.SelectedText = "<End>"
        MyTextBox.SelectionStart = MyTextBox.Text.Length
        k.SuppressKeyPress = True
    End If
End Sub

Note that I’ve also fixed a bug in your code: the assignment of sender to MyTextBox needs an explicit cast! If your original code compiled, you should (!) set Option Strict On. This is essential for improved type checking by the compiler, and should be seen as an unconditional requirement1.

Furthermore, don’t declare variables before you use them. Declare them at the latest possible point, when you first assign a value to them. This makes the program state easier traceable and often results in shorter code.


1 (unless you work a lot with COM late binding, in which case you can disable it on a per-file base).