Andrew Henz Andrew Henz - 1 year ago 114 Question

VB.NET VbNewLine

I have a multilined textbox and this code:

If e.KeyCode = Keys.Enter Then
TextBox1.Text = TextBox1.text + vbNewLine + mystring
End if

The problem is when I hit enter it jumps to the next line instead of going to the new line and position the cursor at the last character.I was thinking about making it somehow press the Back button so it gets back to the line above,but that's not possible.

Answer Source

If this is in the KeyDown event, all you have to do is tell it to not proceed with the actual key press. Because as it stands you're currently adding a new line but so is also the system (since you pressed the ENTER key).

To intercept the actual key press and keeping it from getting passed onto the TextBox, all you have to do is to set the SuppressKeyPress property to True:

If e.KeyCode = Keys.Enter Then
    TextBox1.AppendText(vbNewLine & mystring)
    e.SuppressKeyPress = True
End If

As noted in the comments concatenation should be done with the ampersand (&) operator, and TextBox1.AppendText(...) is better to use since it will make the code easier to read.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download