I hate using the mask edit conrol so I created these two function to
format my phone numbers. Is there a way to consolidate these two
functions into one?
In this example say the textbox you want to format is named "txtTest"
I would format it in this fashion:
in the onchange event:
'Formats the text on entry
txtTest.text = FormatPhoneNumber(sender, txtTest.text)
in the keypress event for txtTest:
'Sends the object textbox and keypress to the ModType Function to
check for backspace...
ModType(sender, e)
Notes: I normaly set StopHypen as a Public Boolean....
Private Function FormatPhoneNumber(ByVal sender As System.Object,
ByVal phone As String) As String
Dim phoneFormater As String
Dim myTextbox As TextBox
myTextbox = CType(sender, TextBox)
If StopHypen = True Then
StopHypen = False
Return Mid((myTextbox.Text), 1, (Len(myTextbox.Text)))
myTextbox.SelectionStart = 7
Exit Function
End If
If dontRunOnLoad = False Then
If phone.Length = 1 And Mid(phone, 1) = "1" Then
phone = ""
phoneFormater = phone
myTextbox.SelectionStart = Len(myTextbox.Text)
myTextbox.SelectionLength = 0
Return (phoneFormater)
ElseIf phone.Length = 1 And Mid(phone, 1) <> "(" Then
phone = "(" & phone
phoneFormater = phone
myTextbox.SelectionStart = Len(myTextbox.Text)
myTextbox.SelectionLength = 0
Return (phoneFormater)
ElseIf phone.Length = 4 Then
phone = phone & ")"
phoneFormater = phone
myTextbox.SelectionStart = Len(myTextbox.Text)
myTextbox.SelectionLength = 0
Return (phoneFormater)
ElseIf phone.Length = 6 And Mid(phone, 6, 1) = "-" Then
phone = Mid(phone, 1, Len(phone) - 1)
phoneFormater = phone
Return (phoneFormater)
ElseIf phone.Length = 5 And Mid(phone, 5, 1) <> ")" Then
phone = Mid(phone, 1, 4) & ")" & Mid(phone, 5, 1)
' (603)1
phoneFormater = phone
Return (phoneFormater)
ElseIf phone.Length = 8 Then
phone = phone & "-"
phoneFormater = phone
myTextbox.SelectionStart = Len(myTextbox.Text)
myTextbox.SelectionLength = 0
Return (phoneFormater)
Else
phoneFormater = phone
myTextbox.SelectionStart = Len(myTextbox.Text)
myTextbox.SelectionLength = 0
Return (phoneFormater)
End If
Else
Return phone
End If
End Function
Private Function ModType(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs)
Dim MyTextBox As TextBox
MyTextBox = CType(sender, TextBox)
If e.KeyChar = ControlChars.Back = True Then
If Len(MyTextBox.Text) <> 9 And Len(MyTextBox.Text) <> 5
Then
MyTextBox.Text = Mid(MyTextBox.Text, 1,
(Len(MyTextBox.Text)))
ElseIf Len(MyTextBox.Text) = 5 Then
StopHypen = True
Else
StopHypen = True
MyTextBox.Text = Mid(MyTextBox.Text, 1, 8)
MyTextBox.SelectionStart = 8
End If
End If
End Function