System.FormatException: Input string was not in a correct format while parsing value to integer and decimal in ASP.Net

Last Reply on Mar 28, 2017 04:52 AM By dharmendr

Posted on Mar 27, 2017 11:06 AM

hi

I used below code to conver textbox value to int:

if (!IsPostBack)
{ 
     int rahn2 = int.Parse(Txtrahn2.Text);
     int rahn1 = int.Parse(Txtrahn1.Text);
}

but this error happen:

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 27:             int rahn2 = int.Parse(Txtrahn2.Text);
Line 28:             int rahn1 = int.Parse(Txtrahn1.Text);
Line 29:         }

Best regards

neda

You are viewing reply posted by: dharmendr on Mar 28, 2017 04:52 AM.
Posted on Mar 28, 2017 04:52 AM Modified on on Mar 28, 2017 04:53 AM
nedash says:
if (!IsPostBack)
{ int rahn2 = int.Parse(Txtrahn2.Text);
    int rahn1 = int.Parse(Txtrahn1.Text);
}

Change above with the below code.

if (!IsPostBack)
{
    int rahn2 = int.Parse(string.IsNullOrEmpty(Txtrahn2.Text) ? "0" : Txtrahn2.Text);
    int rahn1 = int.Parse(string.IsNullOrEmpty(Txtrahn1.Text) ? "0" : Txtrahn1.Text);
}

OR

if (!IsPostBack)
{
    decimal rahn2 = decimal.Parse(string.IsNullOrEmpty(Txtrahn2.Text) ? "0" : Txtrahn2.Text);
    decimal rahn1 = decimal.Parse(string.IsNullOrEmpty(Txtrahn1.Text) ? "0" : Txtrahn1.Text);
}