-
May 23rd, 2018, 09:21 AM
#1
Thread Starter
New Member
[RESOLVED] MaskedTextBox cursor resets to second position when clearing inside .TextChanged
I need to clear MaskedTextBox1 when a user enters 10 inside the textbox.
The problem is that whenever the MaskedTextBox is cleared inside of .TextChanged, the cursor always resets to the second position instead of the first (leftmost position).
If I add a breakpoint inside TextChanged, it works correctly. But without the breakpoint the cursor resets to the second position.
Here is the full code: (simplified to only contain the MaskedTextBox issue)
The mask is 00
Code:
Public Class Form1
Private Sub MaskedTextBox1_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles MaskedTextBox1.TextChanged
If MaskedTextBox1.MaskCompleted Then
If MaskedTextBox1.Text = "10" Then
MaskedTextBox1.Text = ""
'also tried MaskedTextBox1.ResetText() and MaskedTextBox1.Clear() but cursor stays on the second position in the textbox
'tried MaskedTextBox1.Select(0, 0) but the cursor is still on the second position in the textbox
'the following selects the Second character, instead of the first.
MaskedTextBox1.Select(0, 1)
End If
Else
'something else
End If
End Sub
End Class
-
May 23rd, 2018, 07:01 PM
#2
Re: MaskedTextBox cursor resets to second position when clearing inside .TextChanged
It ain't pretty, but it works (hopefully)
There surely must be a more elegant way to solve the problem, but I have been looking for a good half an hour and all I found was more or less "hacks" like this...
Code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Me.MaskedTextBox1.TextChanged, AddressOf MaskedTextBox_TextChanged
End Sub
Private Sub MaskedTextBox_TextChanged(sender As Object, e As EventArgs)
Dim MTextBox As MaskedTextBox = DirectCast(sender, MaskedTextBox)
MTextBox.Mask = "00"
MTextBox.SelectionStart = MTextBox.TextLength - 1
If MTextBox.MaskCompleted Then
If MTextBox.Text = "10" Then
With MTextBox
.Text = String.Empty
.Mask = Nothing
.Select(0, 0)
End With
End If
Else
'something else
End If
End Sub
Last edited by Arve K.; May 23rd, 2018 at 07:05 PM.
-
May 23rd, 2018, 09:37 PM
#3
Thread Starter
New Member
Re: MaskedTextBox cursor resets to second position when clearing inside .TextChanged
That works nicely! Thank you very much!
-
Aug 19th, 2019, 05:09 PM
#4
New Member
Re: [RESOLVED] MaskedTextBox cursor resets to second position when clearing inside .T
I have solved this problem previously using the following code:
maskedtextbox.clear()
maskedtextbox.focus()
sendkeys.send("{HOME}")
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|