所以我有一个带有文本框的表单来输入整数以形成时间,理想的工作程序基本上意味着用户必须先从列表框中选择一个跑步者,然后才能输入任何整数并单击Process
按钮,但是当我没有选择一个跑步者并单击此行引发Process
的错误:NullReferenceException
lblRunnerInfo.Text = lstRunners.SelectedItem.ToString() + "\r\n" + "Finished?: " + "\r\n" + "Time: " + txtHours.Text + ":" + txtMinutes.Text + ":" + txtSeconds.Text;
按钮的完整代码如下:
private void btnProcess_Click(object sender, EventArgs e)
{
// Converts variables attached to textboxes to integers
hoursInt = Convert.ToInt32(txtHours.Text);
minutesInt = Convert.ToInt32(txtMinutes.Text);
secondsInt = Convert.ToInt32(txtSeconds.Text);
// Check if a runner has been selected
if (lstRunners.SelectedIndex > -1)
{
// Obtain selected runner
Runner selectedRunner = (Runner)lstRunners.SelectedItem;
// Call the method in Gate class to process the runner
gate.ProcessRunner(selectedRunner);
}
else
{
MessageBox.Show("Please select a runner!");
}
// Converts the total to a string and outputs it as a label
lblFinished.Text = gate.Total.ToString();
lblRunnerInfo.Text = lstRunners.SelectedItem.ToString() + "\r\n" + "Finished?: " + "\r\n" + "Time: " + txtHours.Text + ":" + txtMinutes.Text + ":" + txtSeconds.Text;
}
我可能缺少一些非常简单的东西,但我以前从未有NullReferenceException
过,所以任何帮助都会很棒。