我创建了一个程序,并对其进行了广泛的测试,我收到一条错误消息,提示“未处理 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");
}
}