Reputation: 1290
I am trying to run the following conversion, which results in an invalid cast exception
specified cast is not valid
settings.ActionTimer = Convert.ToInt32(TimeSpan.FromMinutes((double)ActionTimerComboBox.SelectedValue).TotalMilliseconds);
What this is attempting is the following:
ActionTimerComboBox.SelectedValue
, which in this case is "13" and convert it from object to double so that TimeSpan.FromMinutes() can be applied to it.settings.ActionTimer
to the millisecond converted value, which should be "780000".How can I accomplish this?
Upvotes: 1
Views: 1966
Reputation: 674
This exception is coming from this statement:
((double)ActionTimerComboBox.SelectedValue)
Object to Double conversion is throwing invalid cast exception. Either convert this object to string first and then convert it to double.
((double)ActionTimerComboBox.SelectedValue.toString());
Or, You can also use below code:
var val = ActionTimerComboBox.SelectedValue;
if (val is IConvertible)
{
double d = ((IConvertible)val).ToDouble(null);
}
Upvotes: 0
Reputation: 29036
Everything looks fine except the conversion from ActionTimerComboBox.SelectedValue
to double. And that's the error message also saying. you have to use something like the following:
string comboSelectedValue = ActionTimerComboBox.SelectedValue;
double selectedVal =0.0;
if(double.TryParse(comboSelectedValue, out selectedVal)){
settings.ActionTimer = (int)TimeSpan.FromMinutes(selectedVal).TotalMilliseconds;
Console.WriteLine(TimeSpan.FromMinutes(selectedVal).TotalMilliseconds);
}
else
{
Console.WriteLine("Error in conversion");
}
Working Example HERE. This Link may helps you to know more about type casting.
Upvotes: 3
Reputation: 605
ActionTimerComboBox.SelectedValue is returning string you can't cast it as double, you should try double.Parse(), double.TryParse() Or Convert class as you used here. -sorry couldn't comment
Upvotes: 2