views:

19

answers:

3

hi, 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 '/' Application.

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!

+1  A: 

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.

Will A
+1  A: 

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
}
abatishchev
Perfect answer for parsing a long, but please heed my warning answer that you should never use a long to store a phone number!
Kieren Johnstone
@abatishchev what is "out l" do?
Nagaraj Tantri
@Nagaraj: `out` keyword means passing variable by reference. So in case of success parsing result will be assigned to this variable. Otherwise it will leave its initial value. See more at http://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx
abatishchev
+2  A: 

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.

Kieren Johnstone
@Kieren Johnstone i will implement your suggestion :)but the above answer was perfect with respect to parse :)
Nagaraj Tantri
Agree with no doubt! Just add a `RegularExpressionValidator` or functional similar to check the input, e.g. `"\+[0-9]+ \([0-9]+\) [0-9]+"` for `"+7 (903) 1234567"`
abatishchev