Formatting databound textbox as a phone number in VB.NET

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Maria P
    New Member
    • Mar 2012
    • 4

    #1

    Formatting databound textbox as a phone number in VB.NET

    I have a databound textbox that I would like formatted as a phone number ((###) ###-####), instead of being displayed as 10 numbers.

    I'm using this on a databound label, which works fine. The same doesn't work on a textbox, though.

    phoneNumber = CDbl(lblPhoneNu mber.Text)

    lblPhoneNumber. Text = phoneNumber.ToS tring("(###) ###-####")


    Anyone know of something that will work with a textbox?
  • PsychoCoder
    Recognized Expert Contributor
    • Jul 2010
    • 465

    #2
    Change this:
    Code:
    phoneNumber.ToString("(###) ###-####")
    to this:
    Code:
    phoneNumber.ToString("{0:(###)-###-####}")
    EDIT: You could also use this to accomplish your task:
    Code:
    double phone = double.Parse(txtPhone.Text);
    lblPhoneNumber.Text =  String.Format("{0:###-###-####}", phone);
    Last edited by PsychoCoder; Mar 28 '12, 06:08 AM.

    Comment

    • Maria P
      New Member
      • Mar 2012
      • 4

      #3
      Okay, got it.

      So, was getting some out of bounds for the record when looking at other records (have a form set up where you can view a record at a time).

      So, under the text changed event, I used:

      Code:
      If IsNumeric(txtPhoneNumber.Text) Then
            phoneNumber = CDbl(txtPhoneNumber.Text.Trim)
      End If
      Then under button click events (when moving through records), added:

      Code:
      txtPhoneNumber.Text = phoneNumber
      to set it back to a number, so I don't get an error.

      And then under form load event and binding source position changed event, I have this:

      Code:
      If Not phoneNumber = 0 Then
                  txtPhoneNumber.Text = String.Format("{0:(###) ###-####}", phoneNumber)
      End If
      And it's workin. It'd be nice if it could be a one liner though, like with a label, but whichever lol.


      Thanks for your help.

      Comment

      Working...