John
John

Reputation: 53

TextBox formatting lost when focus changes

I have a Windows Form with data bound textBox which displays a phone number formated like this: (800) 555-5555. The data is stored as decimal and then I display it in the correct format. The problem though is when I click into the textBox and then click on somthing else it changes from (800) 555-5555 back to 8005555555. The formating is lost. I tried reformating the digits again on the textBox leave event but that doesn't work. What could be causing this?

vs 2010 c#

to Format first I do this

private string FormatCustPhoneBox(string a)
{
            string phone = a;

            for (int j = 0; j < phone.Length; j++)
            {
                if (!Char.IsDigit(phone, j))
                {
                    phone = phone.Remove(j, 1);  //Remove any non numeric chars.
                    j--;
                }
            }
            return phone;
}

then i do this

    private void FormatPhoneNum()
    {
        decimal iPhone = decimal.Parse(CustomerPhone1Box.Text);
        CustomerPhone1Box.Text = string.Format("{0:(###) ###-####}", iPhone);
    }

Upvotes: 5

Views: 1414

Answers (1)

hungryMind
hungryMind

Reputation: 7009

Are you binding the data to textbox? If yes, convert data to formatted string and bind to string data type rather than number. Or use masked text box.

Upvotes: 4

Related Questions