开发者

textbox string to long format error

i am doing a project with SQL server 2005 and VS 2008,

I have parsed a textbox text to long variable(phone number), because the backend stores the phone number in bigint.

long phone = long.Parse(TextBox4.Text);

This works fine when i insert my phone number, but if a person doesn't know or doesn't want to insert it, i have the option for phone number as null.

If i just press the submit button without entering the phone number i get this error!!?

Server Error in '/' App开发者_C百科lication.

Input string was not in a correct format.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:    

Line 48:     string deptName = TextBox2.Text;
Line 49:     string deptLoc = TextBox3.Text;
Line 50:     long phone = long.Parse(TextBox4.Text);
Line 51:     string flag = "";

Please rectify my error, I am not understanding which other method to parse it!


A phone number should allow for brackets, spaces, dashes, + symbols, # symbols and of course, loads of phone numbers start with a 0 (and so 01234 567891 becomes 1234567891).

You should always store a phone number as a string. Very few phone numbers can be stored as a long or integer.

Hope that helps.


Parse() can't parse null or incorrect input and throws an error, TryParse() don't:

long l;
if (long.TryParse(textBox.Text, out l))
{
    // success
}
else
{
    // not. probably throw an exception yourself. or just ignore
}


Try the Boolean long.TryParse(string, byref long) method instead. This doesn't throw an exception if the parse fails - instead it returns a boolean.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜