Share via

Set current position in textbox

OSVBNET 1,401 Reputation points
2022-08-01T02:25:34.923+00:00

Hello,
to limit the characters inside the textbox specially when pasting text I use this code in TextBox.TextChanged event:

Dim MySS As Integer = rTextBox.SelectionStart
Dim FileNameFilter As String = String.Empty
For MyLoop As Integer = 0 To rTextBox.TextLength - 1
Select Case Convert.ToInt32( rTextBox.Text.Chars(MyLoop))
Case 32, 45, 46, 48 To 57, ...
FileNameFilter = FileNameFilter + rTextBoxX.Text.Chars(MyLoop)
...
and at the end:
rTextBox.Text = FileNameFilter

Just can't figure out how to keep the position of IBeam cursor where it was before paste!
is that possible?

Developer technologies | VB
0 comments No comments

Answer accepted by question author

Jiachen Li-MSFT 34,241 Reputation points Microsoft External Staff
2022-08-01T06:21:40.437+00:00

Hi @OSVBNET ,
Try the code below.

    Dim lenth As Integer = 0  
    Private Sub MessageTextBox_TextChanged(sender As Object, e As EventArgs) Handles MessageTextBox.TextChanged  
        Dim sel = MessageTextBox.SelectionStart  
        Dim lenth_change = MessageTextBox.TextLength - lenth  
        Dim FileNameFilter As String = MessageTextBox.Text  
        MessageTextBox.Text = ""  
        For MyLoop = 0 To FileNameFilter.Length - 1  
            Select Case Convert.ToInt32(FileNameFilter.Chars(MyLoop))  
                Case 32, 45, 46, 48 To 57, 64, 65 To 90, 97 To 122, 10  
                    MessageTextBox.AppendText(FileNameFilter.Chars(MyLoop).ToString)  
            End Select  
        Next  
        MessageTextBox.SelectionStart = sel  
        If MessageTextBox.TextLength - lenth >= 0 Then  
            MessageTextBox.SelectionStart = MessageTextBox.SelectionStart - (lenth_change - (MessageTextBox.TextLength - lenth))  
        End If  
        lenth = MessageTextBox.TextLength  
    End Sub  

Best Regards.
Jiachen Li

----------

If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.