gpt4 book ai didi

c# - 为什么我收到 FormatException 是未处理的错误?

转载 作者:行者123 更新时间:2023-11-30 19:02:22 24 4
gpt4 key购买 nike

我创建了一个程序,并对其进行了广泛的测试,我收到一条错误消息,提示“FormatException 未处理,输入字符串的格式不正确”。当我将任一文本框留空并按下“完成”按钮时会出现问题,但如果我输入低于 0 或高于 59 的任何内容,它会正常工作——这是我想要允许的数字范围。我该怎么做才能在方框为空时不收到此错误消息?这是我在“btnFinished”背后的代码:

   private void btnFinished_Click(object sender, EventArgs e)
{
if (lstCyclists.SelectedIndex >= 0)
{
Cyclists currentCyc = (Cyclists)lstCyclists.SelectedItem;
//Decalre the minsEntered and secsEntered variables for txtMins and textSecs
int minsEntered = int.Parse(txtMins.Text);
int secsEntered = int.Parse(txtSecs.Text);

try
{
//If the status of a cyclist is already set to Finished, show an error
if (currentCyc.Finished.ToString() == "Finished")
{
MessageBox.Show("A time has already been entered for this cyclist");
}
else
{
//if a minute lower than 0 or greater than 59 has been entered, show an error
if (minsEntered < 0 || minsEntered > 59)
{
MessageBox.Show("You can only enter a minute up to 59");
}
//if a second lower than 0 or greater than 59 has been entered, show an error
else if (secsEntered < 0 || secsEntered > 59)
{
MessageBox.Show("You can only enter a second up to 59");
}
else
{
//otherwise, set the status to finished and update the time
currentCyc.Finished = "Finished";
currentCyc.FinishedHours(Convert.ToInt32(txtHours.Text));
currentCyc.FinishedMins(Convert.ToInt32(txtMins.Text));
currentCyc.FinishedSecs(Convert.ToInt32(txtSecs.Text));
//pass the parameter to the scoreboard class to display it in lblCyclistsFinished
lblCyclistsFinished.Text += "\n" + finishLine.Scoreboard(currentCyc);
//add to the number of cyclists finished
Cyclists.NumFinished++;
lblnumFinished.Text = Cyclists.NumFinished.ToString();
//update the details box
DisplayDetails(currentCyc);
txtHours.Clear();
}
}
}
catch
//make sure all the time fields have been entered, otherwise show an error message
{
MessageBox.Show("Please ensure all time fields have been entered");
}
}
else
//make sure a cyclist has been selected when pressing "Finished", otherwise show an error message
{
MessageBox.Show("You must select a cyclist");
}
}

最佳答案

好吧,看看这些行:

int minsEntered = int.Parse(txtMins.Text);
int secsEntered = int.Parse(txtSecs.Text);

当文本框为空白时,您期望返回什么?

不要为空文本框调用 int.Parse。例如:

int minsEntered = txtMins.Text == "" ? 0 : int.Parse(txtMins.Text);
// Ditto for seconds

当然,如果您输入非数字内容,这仍然会出错。您可能应该改用 int.TryParse:

int minsEntered;
int.TryParse(txtMins.Text, out minsEntered);

在这里,我忽略了 TryParse 的结果,并且无论如何它都会将 minsEntered 保留为 0 - 但如果您想要不同的默认值,您可以使用类似:

int minsEntered;
if (!int.TryParse(txtMins.Text, out minsEntered))
{
minsEntered = 5; // Default on parsing failure
}

(或者您可以在这种情况下显示错误消息...)

关于c# - 为什么我收到 FormatException 是未处理的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13312411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com