1

I have a program that has 3 items in the form. A phone number textbox, datagridview, and a button. I want to be able to click the button and transfer the numbers from the phone number textbox to the datagridview, but instead of the numbers showing up like this: 1234567891 in the datagridview. I want the format of the phone numbers showing up like this (123) 123 – 1234. I’ve searched for hours on the internet, but I couldn’t figure out a good way to do this.

  • why don't you use a masked textbox instead of a normal one? – Keith Mifsud Jul 02 '15 at 07:55
  • possible duplicate of [How to format a string as a telephone number in C#](http://stackoverflow.com/questions/188510/how-to-format-a-string-as-a-telephone-number-in-c-sharp) – Fabio Jul 02 '15 at 12:41

1 Answers1

0

It sounds like you want the DataGridView to store the number as unformatted but display it as formatted. I'm not sure if you can do that or not, but the good news is, you don't need to. Why not simply store the unformatted number however you want and then pass the DataGridView the formatted number using a separate variable?

Dim UnformattedNumber As String = TextBox1.Text
Dim FormattedNumber As String = FormatNumber(UnformattedNumber)

Public Function FormatNumber(ByVal PhoneNumber As String) As String
    If Not String.IsNullOrWhiteSpace(PhoneNumber) _
    AndAlso len(PhoneNumber) = 10 _
    AndAlso IsNumeric(PhoneNumber) Then
        FormatNumber = "(" & Left(PhoneNumber, 3) & ") " _
        & Mid(PhoneNumber, 4, 3) & " - " _
        & Right(PhoneNumber, 4)
    Else
        FormatNumber = ""
    End If
End Function

You can still refer to UnformattedNumber from a DataGridView event if you need to.

Note that if you place this function inside a Form, you will need to preface Left and Right with Microsoft.VisualBasic.Strings..

Josh
  • 1,088
  • 1
  • 7
  • 16