A format exception, according to the documentation means:
value does not consist of an optional sign followed by a sequence of digits (0 through 9).
Whatever you’re getting on this line:
string test = listBox2.SelectedItem.ToString().Trim();
Is not an parse-able integer. You should debug to figure out what the value is that you’re actually getting.
Hint: Trim
does not grab the first character of the string. A quick google for some code examples on how to grab a substring or the first character of a string should find you what you need.
Once you’ve figured out getting the first character correctly, you can either wrap your code in a try-catch (example from the documentation):
try {
result = Convert.ToInt32(value);
Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.",
value.GetType().Name, value, result.GetType().Name, result);
}
catch (OverflowException) {
Console.WriteLine("{0} is outside the range of the Int32 type.", value);
}
catch (FormatException) {
Console.WriteLine("The {0} value '{1}' is not in a recognizable format.",
value.GetType().Name, value);
}
Or you can use TryParse
and look at the boolean result to see if the parse completed successfully.