FormatException was unhandled Input string was not in a correct format

I want to get an int value from my database. I have error FormatException was unhandled Input string was not in a correct format.

My code is

       string str = doc_cell.Text;
       ulong a = Convert.ToUInt64(str);

Upvotes: 0

Views: 119

Answers (2)

try
{
    string str = doc_cell.Text;
    ulong a = Convert.ToUInt64(str);
}
catch (FormatException)
{
    MessageBox.Show("Error");
}

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

The problem comes because the string which you convert is not UInt64, because of that this line throws an exception.

You should write it like this:

UInt64 a =0;
bool isSuccess = UInt64.TryParse(str, out a);

In this case you will have the value of the string in the a, if the parsing is successful. If the parsing is not you will have 0 in a.

Upvotes: 1

Related Questions