Reputation: 7590
In Asp.net using c# ,I am having
int sum = Convert.ToInt32(txtbox1.Text) + Convert.ToInt32(txtbox2.Text);
When i have an empty textbox, i get the error "Input string is not in a correct format".
So, I am wondering if there is a simple way to add textbox values only they are integers, if not take the textbox value as 0.
Thanks in advance!
Upvotes: 0
Views: 3951
Reputation: 152521
You can either set the default value of the TextBox
to 0
, or use TryParse
:
int val1, val2;
Int.TryParse(txtbox1.Text,out val1));
Int.TryParse(txtbox2.Text,out val2));
int sum = val1 + val2;
Note that you do not need to set the values to 0 if the parse fails since they will be 0 anyways. If you want to be explicit, however:
int val1, val2;
if(!Int.TryParse(txtbox1.Text,out val1))) val1 = 0;
if(!Int.TryParse(txtbox2.Text,out val2))) val2 = 0;
int sum = val1 + val2;
Upvotes: 1
Reputation: 48076
Use try parse to ensure that the textbox's contain valid input (that or limit the input to only numbers).
int x, y, result;
if (int.TryParse(txtbox1.Text, x)
{
if (int.TryParse(txtbox2.Text, y)
{
result = x + y;
}
else
//error message
}
else
// error message
Upvotes: 1
Reputation: 8664
use TryParse ..
int iFirstVal= 0;
int iSecondVal= 0;
int.TryParse(txtbox1.Text, out iFirstVal))
int.TryParse(txtbox2.Text, out iSecondVal))
int sum = iFirstVal + iSecondVal
Upvotes: 0
Reputation: 63956
Write an Extension method for this
public static int NullOrEmptyToZero(this string s)
{
return string.IsNullOrEmpty(s)? 0: ConvertToInt32(s);
}
And use it like so:
int sum = txtbox1.Text.NullOrEmptyToZero() + txtbox2.Text.NullOrEmptyToZero();
Upvotes: 1
Reputation: 1900
int integer;
Int32.TryParse(Textbox1.Text, out integer)
int integerSecond
Int32.TryParse(Textbox2.Text, out integerSecond)
It will return a bool so you can see if they entered a valid integer
Alternatively you could also use some validators:
<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer"
ControlToValidate="ValueTextBox" ErrorMessage="Value must be a whole number" />
If there is a specific range of values that are valid (there probably are), then you can use a RangeValidator, like so:
<asp:RangeValidator runat="server" Type="Integer"
MinimumValue="0" MaximumValue="400" ControlToValidate="ValueTextBox"
ErrorMessage="Value must be a whole number between 0 and 400" />
Upvotes: 1