【发布时间】:2014-03-07 06:31:53
【问题描述】:
我有:
private void btnAddScore_Click(object sender, EventArgs e)
{
if (IsInt32())
{
txtScores.Text += txtScore.Text + " ";
txtScore.Text = "";
}
}
和:
private void button2_Click(object sender, EventArgs e)
{
if (IsValidData())
{
List<string> result = txtScores.Text.Split(' ').ToList();
student = new Student(txtName.Text, result.Select(int.Parse).ToList());
this.Close();
}
}
我正在尝试使用我的 btnAddScore 来构建从我的 txtScore 到我的 txtScores 的分数字符串。我相信我做得对。然后我通过用“”解析每个元素将该字符串转换为列表。然后我进一步将 List 转换为 List 。没有编译器错误,但运行时错误“FormatException was unandled”并指向 (int.Parse)。我读过 int.Parse 如果在空字符串上使用会导致这种情况,但我不明白如果是这样的话。
【问题讨论】:
-
异常时
txtScores.Text的值是多少 -
使用 int.TryParse。我怀疑您尝试转换的字符串不是数字格式
-
放一些IsInt32方法的细节
-
我注释掉了 IsInt32 并在没有验证器的情况下运行它(这就是 IsInt32,我相信你知道)。还是一样的结果。私人 bool IsInt32(){try {Convert.ToInt32(txtScore.Text);返回真; } catch (FormatException) {MessageBox.Show(txtScore.Tag + "必须是整数。"); txtScore.Focus();返回 false;}}
-
我可以直接在 txtScores {100 20 40} 中输入我想要的格式的分数字符串,它工作得很好。我应该使用 txtScores.Text += txtScore.Text + " "; 在同一个框中输入相同的分数。它是作为字符串输入的,不是吗?
标签: c# linq parsing formatexception