Reputation: 1073
I have a masked textbox with input mask as A-00-000-0000
It gets data from database. Like
Is there any way to set caret position to specific position as mentioned above?
Upvotes: 1
Views: 3584
Reputation: 1073
After optimizing my codes, my logic is to move caret at desired location, independen of mask, And remove string after that location..
''' <summary>
''' Set Caret Position to specific location and remove data After given Location
''' </summary>
''' <param name="MaskedTb"> Masked textbox</param>
''' <param name="Loct99">Location (Index) after which remove occured and caret is set</param>
''' <remarks></remarks>
Public Sub FocsToMaskedTb( MaskedTb As MaskedTextBox, ByVal Loct99 As Integer)
If MaskedTb.Text.Length >= Loct99 Then
MaskedTb.Text = MaskedTb.Text.Remove(Loct99)
End If
MaskedTb.SelectionStart = MaskedTb.MaskedTextProvider.LastAssignedPosition + 1
'' I am using MaskedTextProvider Property
'' If there is nothing in TextBox, MaskedTb.MaskedTextProvider.LastAssignedPosition = -1
End Sub
Upvotes: 0
Reputation: 9981
A simple way is to use a reverse loop and check each char. If it's not a Hyphen
nor a Space
then you've reached the end of the input string.
Dim text As String = Me.MaskedTextBox1.Text
Dim index As Integer = 0
Dim character As Char = Nothing
For index = text.Length To 1 Step -1
character = text.Chars((index - 1))
If ((character <> "-"c) AndAlso (AscW(character) <> 32)) Then
Exit For
End If
Next
Me.MaskedTextBox1.Focus()
Me.MaskedTextBox1.[Select](index, 0)
Upvotes: 1
Reputation: 197
you might wanna try something like this:
textBox1.Focus();
textBox1.SelectionStart = 8;
textBox1.SelectionLength = 0;
(selectionStart sets the position - length is 0 so nothing is selected).
so in your case, you'd set SelectionStart to 8, then to 3, then to 7...
make sure to set focus to this textBox/Maskedtextbox first, otherwise it won't work...
Edit: you'll have to make sure that after setting the text to the values from the DB, the caret-position is calculated respecting the mask-characters.
Edit2: like this i can set the Position wherever i want - just, 4 will set the position to position 4 respecting the mask. If i omit SelectionStart and SelectionLength, the caret is positioned automatically to the last character inserted by the first line.
maskedTextBox1.Text = "A018";
maskedTextBox1.Focus();
maskedTextBox1.SelectionStart = 7;
maskedTextBox1.SelectionLength = 0;
Upvotes: 1