0

したがって、整数を入力して時間を形成するためのテキストボックスを備えたフォームがあり、理想的な作業プログラムは、基本的に、ユーザーが整数を入力して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ので、どんな助けも素晴らしいでしょう.

4

3 に答える 3

3

このステートメントを置き換えます

if (lstRunners.SelectedIndex > -1)

これとともに:

if (lstRunners.SelectedItems.Count > 0)
于 2013-11-01T19:30:20.263 に答える
2

A NullReferenceException occurs when you try to access an object that is null. For example, calling myString.ToString() when myString is null causes an ex.

In your code:

lblRunnerInfo.Text = lstRunners.SelectedItem.ToString() + "\r\n" + "Finished?: " + "\r\n" + "Time: " + txtHours.Text + ":" + txtMinutes.Text + ":" + txtSeconds.Text;

These items appear to be controls added by the designer. Calling the Text property on such controls is perfectly fine because they are initialized by the designer code. The problem is with Selector.SelectedItem. From MSDN we know this property can return null:

Gets or sets the first item in the current selection or returns null if the selection is empty.  

So you need to perform a null check:

        string selectedItemText = "";
        string newline = Environment.NewLine;
        if(lstRunners.SelectedItem != null)
        {
           selectedItemText = lstRunners.SelectedItem.ToString() 
        }            
        string result = String.Format("{0}{1}Finished?: {1} Time: {3}:{4}:{5}",selectedItemText, newline,txtHours.Text,txtMinutes.Text,txtSeconds.Text);
        lblRunnerInfo.Text = result;
于 2013-11-01T19:41:44.063 に答える