don't know how to convert properly - c#

int a = Convert.ToInt32(subjectsLabel1.Text);
int b = int.Parse(internetLabel1.Text);
int total = a+b;
label1.Text = total.ToString();
the error "Input string was not in a correct format." keeps poping out.
I tried to convert using the "int.parse" and the "convert.toint32" syntax but the same error keeps showing up.
*the values in the subjectsLabel1 and internetlabel1 would be coming from the database (which was done in visual studio) w/ datatype varchar(10).

There is nothing wrong with the way you are parsing those string values to integers. It's just that their value doesn't represent a valid integer so it cannot be parsed and an exception is thrown. You could use the int.TryParse method to handle gracefully this case:
int a;
int b;
if (!int.TryParse(subjectsLabel1.Text, out a))
{
MessageBox.Show("please enter a valid integer in subjectsLabel1");
}
else if (!int.TryParse(internetLabel1.Text, out b))
{
MessageBox.Show("please enter a valid integer in internetLabel1");
}
else
{
// the parsing went fine => we could safely use the a and b variables here
int total = a + b;
label1.Text = total.ToString();
}

If you're not sure the user is giving you a legal Int32 value to convert you can use:
int result;
if (!int.TryParse(subjectsLabel.Text, out result))
{
ShowAMessageToTheUser();
}
else
{
UseResult();
}
Using TryParse won't trow an exception when you try to parse a string. Instead it will return false and the out parameter is not valid to use.

You Cannot convert to Int32 if the string contains a decimal pointor its not a valid integer .Check
string test = "15.00"
int testasint = Convert.ToInt32(test); //THIS WILL FAIL!!!
Because Int32 does not support decimals. If you need to use decimals, use Float or Double.
So in this situation you can use
int.TryParse
also

Related

Input string was not in a correct format. Textchange problem [duplicate]

This question already has answers here:
Input string was not in a correct format
(9 answers)
Closed 3 years ago.
C# CODE
I have a problem with my "Check in" form.
I want to multiply the txtsubtotal and txtadvancepayment.
In textchange if I put number on the txtadvancepayment, the overallresult is correct. But if I clear the txtadvancepayment (Incase when the user puts a wrong value) it would be error. The error says "Input string was not in a correct format."
What should I do?
My Code downward
int overalltotal = 0;
int a = Convert.ToInt32(txtsubtotal.Text);
int b = Convert.ToInt32(txtadvancepayment.Text);
overalltotal = a - b;
txttotalbalance.Text = overalltotal.ToString();
An empty string cannot be parsed as an int. As others have mentioned, you can use int.TryParse which accepts a string as the first parameter and an out int as the second parameter, which holds the parsed value. You could do this:
int overallTotal = 0;
int a = 0;
int b = 0;
// TryParse returns a bool
// If either of these fails, the variable a or b will keep the default 0 value
int.TryParse(txtSubtotal.Text, out a);
int.TryParse(txtAdvancePayment.Text, out b);
// Sum a and b
overallTotal = a + b;
If you want to show an error to the user that one or both fields isn't a valid integer, you can assign a bool variable such as var aIsNumber = int.TryParse(...) and then check if aIsNumber or bIsNumber is false. If so, then a and/or b could not be parsed to an int.
You could use Int32.TryParse.
Int32.Parse attempts to convert the string representation of a number to its 32-bit signed integer equivalent and returns value indicates whether the operation succeeded. This would mean, in case your textbox is empty or contains a invalid numeric representation, and the method would return false since it would not be able to convert it to int32
For example
if(Int32.TryParse(txtsubtotal.Text,out var a)
&& Int32.TryParse(txtadvancepayment.Text,out var b))
{
// Code which requires a and b
}

Input string was not in a correct format. Expected type in Decimal type

I am not inserting any value in VOUCHER_NO column and updating it.
But it is giving me error as
Input string was not in a correct format.Couldn't store <> in VOUCHER_NO Column. Expected type is Decimal.
Below is my code
drpayinfo[0]["VOUCHER_NO"] = e.Record["VOUCHER_NO"];
Update
I am using Oracle DB and its datatype is NUMBER (10)
Seems your e.Record["VOUCHER_NO"] have some unwanted content which is not convertible to decimal. Try this way checking before assignment or conversion
if(e.Record["VOUCHER_NO"] != "")
{
drpayinfo[0]["VOUCHER_NO"] = Convert.ToDecimal(e.Record["VOUCHER_NO"]);
}
But more safer way to detect and ignore bad content is
decimal result;
if (Decimal.TryParse(e.Record["VOUCHER_NO"], out result))
{
drpayinfo[0]["VOUCHER_NO"] = result;
}
else
{
// do stuff if failed to parese
}
Based on your comments on other answers, your value is an empty string. This cannot directly be converted to a decimal. You must decide some action to take instead.
They following code will try to convert it, and take an action if not. TryParse is your friend for conversions!
decimal num = 0;
if (!Decimal.TryParse(e.Record["VOUCHER_NO"], out num))
{
//Throw some error, maybe set num to some default and assign...
//The appropriate action in this situation depends on your needs.
}
else
{
//You can safely assign the value
drpayinfo[0]["VOUCHER_NO"] = num;
}

convert string to int error in c#

Hello I am trying to convert String to Integer.
The code below shows a part from where I am trying to convert my string to integer.
if (other.gameObject.CompareTag("PickUp"))
{
if ( checkpointboolean == false)
{
string pickupName = other.ToString(); //other = Pickup4
//Remove first 6 letters thus remaining with '4'
string y = pickupName.Substring(6);
print(y); // 4 is being printed
int x = 0;
int.TryParse(y, out x);
print (x); // 0 is being printed
I also tried the below code and instead of '0' I am getting the following error:
if (other.gameObject.CompareTag("PickUp"))
{
if ( checkpointboolean == false)
{
//Get Object name ex: Pickup4
string pickupName = other.ToString();
//Remove first 6 letters thus remaining with '4'
string y = pickupName.Substring(6);
print(y);
int x = int.Parse(y);
FormatException: Input string was not in the correct format
System.Int32.Parse (System.String s)
int.TryParse returns a boolean, true if it succeeded and false if not. You need to wrap this in a if block and do something with that logic.
if(int.TryParse(y, out x))
print (x); // y was able to be converted to an int
else
// inform the caller that y was not numeric, your conversion to number failed
As far as why your number is not converted I could not say until you post what the string value is.
Your first attempt is the best for this case, that code works fine, The int.TryParse() giving 0 to the out parameter and returns false means the conversion is failed. The input string is not in the correct format/ it cannot be converted to an integer. You can check this by using the return value of the int.TryParse(). For this what you need to do is :-
if(int.TryParse(y, out x))
print (x); //
else
print ("Invalid input - Conversion failed");
First of all, ToString() usually uses for debug purpose so there's no guarantee that
other.ToString()
will return the expected "Pickup4" in the next version of the software. You, probably, want something like
int x = other.gameObject.SomeProperty;
int x = other.SomeOtherProperty;
int x = other.ComputePickUp();
...
If you, however, insist on .ToString() you'd rather not hardcode six letters (the reason is the same: debug information tends to change from version to version), but use regular expressions or something:
var match = Regex.Match(other.ToString(), "-?[0-9]+");
if (match.Success) {
int value;
if (int.TryParse(match.Value, out value))
print(value);
else
print(match.Value + " is not an integer value");
}
else
print("Unexpected value: " + other.ToString());

int.TryParse not working

My code is like this
string asd = "24000.0000";
int num2;
if (int.TryParse(asd, out num2))
{
// It was assigned.
}
Now code execution never enters to if case, that means try parse is not working. Can any one tell me whats wrong with the code.
Note:In first step The value 24000.0000 is purposefully assigned as string .
Use the second TryParse overload that allows you to specify NumberStyle parameters to allow for decimals.
int val =0;
var parsed = int.TryParse("24000.0000",
NumberStyles.Number,
CultureInfo.CurrentCulture.NumberFormat,
out val);
For an int, you cannot have decimal places.
EDIT:
string asd = "24000.000";
int dotPos = asd.LastIndexOf('.');
if (dotPos > -1) {
asd = asd.Substring(0, dotPos);
}
int num2;
if (int.TryParse(asd, out num2))
{
// It was assigned.
}
EDIT:
As pointed out by other answers, there are better ways to deal with the conversion.
See the remarks section of the MSDN documentation on this method:
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
The string can only contain whitespace, a sign, and digits.
This should work for you:
string asd = "24000.0000";
int num2;
decimal tmpNum;
if (decimal.TryParse(asd, out tmpNum))
{
num2 = (int)tmpNum;
// It was assigned.
}
You've asked it to parse an int but given it a double or float. Since it can't parse the number it'll return false and set num2 to zero.

convert variable in asp.net

I wrote a piece of simple code that I dont to find what the problem.
the code is:
var sortSecurities="SELECT * FROM securities";
int total=0;
var value="";
foreach(var row in db.Query(sortSecurities))
{
value=row.lastGate;
total=Convert.ToInt32(value)*100;// here the problem with compilation..
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
what the problem with the convert?
the error is:
Exception Details: System.FormatException: Input string was not in a correct format.
value does not hold a value that can be converted to Int32. If you could do some debugging and see what the value of it is from row.lastGate, you might see what the problem is.
Also, not sure what is returned by db.Query(sortSecurities) (or really what kind of object row.lastGate is), but you can also try to change value=row.lastGate; to value=row.lastGate.ToString();
you can use try parse to check if the value actually contains a number
int total;
bool result = Int32.TryParse(value, out total);
if (result)
{
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
Your value isn't successfully being parsed by Convert.ToInt32()
Alternatively, consider using Int32.TryParse() and validate if the data is indeed the type of data you're expecting.
int result;
if(Int32.TryParse(row.lastGate, out result))
{
//row.lastGate was a valid int
total = result * 100;
}
else
{
//row.lastGate wasn't a valid int
}
Thanks you for all... I try now and found elegant answer.
Like I wrote in the comments, becouse I know that the value of row.lastGate
represent a number I don't need to check it.
So I try this and it works:
var sortSecurities="SELECT * FROM securities";
int total=0;
double value=0;
foreach(var row in db.Query(sortSecurities))
{
value=Convert.ToDouble(row.lastGate);
total=Convert.ToInt32(value)*100;//100 is default
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
Probably I needed to change the value first of all to double and then to int
Becouse when I try to change it directly to int the Compiler did'nt interpret the
string right, becouse of the dot in the number (type double).
thanks about the the intention..

Categories