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

Last Reply one year ago By dharmendr

Posted one year ago

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

Posted one year ago
Hi @nedash,
Please try the following

Input string was not in a correct format.

It might help you.

Cheers Andrea.

Posted one year ago

I change code like:

decimal rahn2 = decimal.Parse (Txtrahn2.Text);

but again error happen...

 


Posted one year ago
nedash says:
Txtrahn2.Text

 What the value you are passing in Txtrahn2.Text


Posted one year ago
dharmendr says:
 What the value you are passing in Txtrahn2.Text

 nothing below are codes:

<asp:UpdatePanel ID="UpdatePanel7" runat="server">
                                                <ContentTemplate>
                            <div id="AmFoD12" runat="server" >
 <asp:TextBox ID="Txtrahn2" runat="server" CssClass="vadi1"></asp:TextBox>
                                 <asp:TextBox ID="Txtrahn1" runat="server" CssClass="vadi2"></asp:TextBox>

                            </div>
                                                      </ContentTemplate>
                                   </asp:UpdatePanel>

 

Best regards

neda

 


Posted one year ago Modified on one year ago
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);
}