Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBox formatting lost when focus changes

Tags:

c#

winforms

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);
    }
like image 702
John Avatar asked Oct 11 '22 13:10

John


1 Answers

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.

like image 70
hungryMind Avatar answered Nov 14 '22 23:11

hungryMind