我得到Formart Exception未得到处理。帮助...
我试图将列表框中字符串的第一个字符转换为int。
listBox2.Items.Add(" 1 " + seatArray[0].PrintInfo);
// I take the first char in the string
string test = listBox2.SelectedItem.ToString().Trim();
//convert to int, here Im getting Formart Exception was unhandled
int num = Convert.ToInt32(test);
//so i can use that int and summon the value A in the seat class.
textBox2.Text = seatArray[num].A.ToString();
这是班级
public class Seats
{
public char A;
public char B;
public char C;
public char D;
public char E;
public char F;
public Seats()
{
A = '.';
B = '.';
C = '.';
D = '.';
E = '.';
F = '.';
}
这就是所以我可以将列表框中类的对象的每个值(ABC DEF)带到右边的文本框中。
答案 0 :(得分:0)
格式例外,根据the documentation表示:
value 不包含可选符号后跟一系列数字(0到9)。
无论你在这条线上得到什么:
string test = listBox2.SelectedItem.ToString().Trim();
不是可解析的整数。您应该调试以确定您实际获得的值。
提示:Trim
没有获取字符串的第一个字符。一个关于如何获取子字符串或字符串的第一个字符的一些代码示例的快速谷歌应该找到你需要的。
一旦你想出正确获得第一个字符,你可以将你的代码包装在try-catch中(例子来自文档):
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);
}
或者您可以使用TryParse
并查看布尔结果以查看解析是否成功完成。