Im using the Mahapps.Metro framework for my C#, Wpf Application.
In the framework is the wpf element: NumericUpDown.
Now I used the element like this:
<Controls:NumericUpDown Name="numCreateArticleStock" Minimum="0"/>
Now I want to convert the entered value in the field into a int value.
Here is my try:
int articleStock = 0;
if(!Int32.TryParse(numCreateArticleStock.Value, out articleStock)
{
await this.ShowMessageAsync("Error", "Error - Message");
}
I get this error:
Cannot convert "double?" in "string"
Maybe someone of you have an Idea, Thanks!
The error you get is because the TryParse method expects as string value, but you have a double? value.
There is no need to parse the value, you can just convert it from double:
int articleStock = (int)numCreateArticleStock.Value.GetValueOrDefault();
The GetValueOrDefault method will turn a null value into 0, I assume that's what you want when there is no value to get from the control.
Since numCreateArticleStock.Value is a double? why not just check if it is null and then cast it to int if it is not null.
int articleStock = 0;
if(!numCreateArticleStock.Value.HasValue)
{
// value is null decide what to do in that case.
}
else
{
articleStock = (int)numCreateArticleStock.Value.Value;
}
Related
I am trying to read my database. I have an column stores int values or null values. When I try to read this column i normally use this line of code;
int Score = Convert.ToInt32(reader["Score"]);
but it can be null. So i cant convert it to int. Then I tried ;
bool tryGetScore = int.TryParse(reader["Score"], out player1Score);
but i cant parse this value neither. It says "Cannot convert from 'Object' to 'System.ReadOnlySpan'"
How can i read this value. Whenever i face a null, my program crashes
You can try use isDbNull for example
int scoreIdx = reader.GetOrdinal("Score");
int score = reader.IsDbNull(scoreIdx) ?
0 : reader.GetInt32(scoreIdx);
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;
}
I'm trying convert decimal? to int and storing the result in "DayOffset". But because of some reason the value of "DayOffset" is getting set to 0 when I run my code. A value is passed in numberRangeHigh as 4
This is what my code looks like:
int DayOffset:
try
{
parseSuccess = int.TryParse(numberRangeHigh.ToString(), out DayOffset);
}
catch (Exception ex)
{
_foundationService.LogBusinessError(null, new ParameterBuilder(), ex.Message.Replace(" ", "_"));
return false;
}
Why are you converting to string at all? To convert decimal? to int, you should just use a cast:
int dayOffset = 0;
if (numberRangeHigh != null)
dayOffset = (int)numberRangeHigh.Value;
The code above will truncate the decimal, so 4.7 would become 4. If you want to round, use Convert.ToInt32 instead:
dayOffset = Convert.ToInt32(numberRangeHigh.Value);
As a side note, the correct way to use TryParse is this:
int DayOffset:
if (!int.TryParse(numberRangeHigh.ToString(), out DayOffset))
{
// Handle error...
return false;
}
Assuming numberRangeHigh is of type Decimal, try this:
int DayOffset = Decimal.ToInt32(numberRangeHigh);
For any nullable struct (you mentioned it was a decimal?), it's often a good idea to first check the .HasValue property (in case it's null). You could do something like this:
int dayOffset = (numberRangeHigh.HasValue) ? Convert.ToInt32(numberRangeHigh.Value) : 0;
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..
I want to convert a value entered in a textBox (which can only be empty or "1" or "2" or "3") to an integer. If empty I want it to be 0, otherwise, it's corresponding value (1, 2, or 3).
Is there a way to do that like:
MyIntVal = TryConvertToInt(textBox1.Text, 0);
...where an empty string or anything not readily convertible to an int would default to 0?
You can use the Int32.TryParse Method:
int myIntVal;
if (!int.TryParse(textBox1.Text, out myIntVal))
{
myIntVal = 42;
}
If the method returns false, the text could not be parsed. myIntVal will be 0 in this case; you can assign a different default value to your variable as shown above.
int result = 0;
int.TryParse(stringValue, out result);
Will default to 0 if stringValue cannot be parsed to an int.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
There's the static TryParse. It returns true if it works.
int myIntVal;
int.TryParse(textBox1.Text, out myIntVal);