0

So I have a form with textboxes to input integers to form a time and the ideal working program basically means that the user has to select a runner from the listbox before they can type in any integers and click the Process button, but when I don't select a runner and click Process the NullReferenceException error is thrown for this line:

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

The full code for the button is as follows:

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;
}

There may be something really simple I am missing, but I've never had a NullReferenceException before, so any help would be great.

Brandon
  • 645
  • 5
  • 13
  • 2
    "I've never had a `NullReferenceException` before, so any help would be great." First project? Debugging those is something that every .NET developer probably runs into way more often than they'd like. Just put a breakpoint on that line and see what's null. I'm guessing it's `lstRunners.SelectedItem`. Then do something to fix it: what should happen when someone clicks Process without selecting a runner? Should they even be allowed to do that, or should you have disabled the button? – Tim S. Nov 01 '13 at 19:21
  • Yeah I want the button to be disabled until the user selects a runner. –  Nov 01 '13 at 19:25
  • Read this [answer](http://stackoverflow.com/a/4660186/2530848). that will help you. – Sriram Sakthivel Nov 01 '13 at 19:26
  • You should attach to `lstRunners`'s [`SelectedValueChanged`](http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.selectedvaluechanged.aspx) event to enable and disable your button. – Tim S. Nov 01 '13 at 19:28
  • Thanks, got it to work! –  Nov 01 '13 at 19:56

3 Answers3

3

replace this statement

if (lstRunners.SelectedIndex > -1)

with this:

if (lstRunners.SelectedItems.Count > 0)
Sudhakar Tillapudi
  • 24,787
  • 5
  • 32
  • 62
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;
P.Brian.Mackey
  • 39,360
  • 59
  • 210
  • 327
1

Most likely the culprit is that lstRunners.SelectedItem is coming back as null. Try adding a conditional check for null, like this:

if (lstRunners.SelectedItem != null)
{
   // 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;
}

More about NRE's here, here and here.

Community
  • 1
  • 1
Brian
  • 5,064
  • 7
  • 33
  • 44