0

Ok, so I have been trying to get a summary of the total number of pieces , number of workers, total pay, and average pay for all employees in this assignment. However, I keep getting an error message when I click the "Summary button" in my program while it is running. "An unhandled exception of type 'System.NullReferenceException' occurred in EX0406.exe Additional information: Object reference not set to an instance of an object."

That is the error message I receive. I'm not quite sure what to do.

My code is not complete seeing that I am stuck, but I would appreciate any help on how to get my summary to display. I am new to programming. If I need to be more specific, please let me know.

Here is what I have:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace EX0406
{
    public partial class PieceworkForm : Form
    {    //class variables 
        private string name;
        private int pieces;
        private string Average_Pay_Per_PERSON;
        private decimal total_Pay; 


        private List<MyData> MyList = new List<MyData>();

        public PieceworkForm()
        {
            InitializeComponent();
        }

        private void calculateButton_Click(object sender, EventArgs e)
        {
            //does the calculations 

            string name = (EmployeeNameTextBox).Text;
            int pieces = Convert.ToInt32(NumOfPiecesText.Text);

            if (name == "")
               MessageBox.Show("You must enter a name.");
            else if (pieces < 1 || pieces > 799)
               MessageBox.Show("Enter a number between 1 and 799.");
            else
            {
               MyData data = new MyData(name, pieces);
               MyList.Add(data);
               MessageBox.Show(string.Format("Amount Earned: {0:C}", data.Paid));
            }

        } 

        private void summaryButton_Click(object sender, EventArgs e)
        {       
            //Display info in msg box
            MyData data = new MyData(name, pieces);

            MyList.Add(data);

            try
            {
                string summaryString = ""
                                     + pieces.ToString()
                                     + "\n\n" + "Total pay:"
                                     + total_Pay.ToString("C")
                                     + "\n\n" + "Average pay per person:"
                                     + Average_Pay_Per_PERSON.ToString();

                MessageBox.Show(summaryString, "Summary:");
            }
            finally
            { 
                MessageBox.Show(SummaryOutPut.Text);  
            }
        }

        private void clearButton_Click(object sender, EventArgs e)
        {   //clears the employee and number of pieces text box
            EmployeeNameTextBox.Clear();
            NumOfPiecesText.Clear();
        }

        private void clearAllButton_Click(object sender, EventArgs e)
        {
            EmployeeNameTextBox.Clear();
            NumOfPiecesText.Clear();
            SummaryOutPut.Clear(); 
        }

        private void exitButton_Click(object sender, EventArgs e)
        {   //closes the program when user clicks exit
            this.Close(); 
        }

        private void nameTextBox_TextChanged(object sender, EventArgs e)
        {

        }



        public class MyData
        {

            public MyData(string name, int pieces)
            {
                //if else statements 
                Name = name;

                Pieces = pieces;
                if (Pieces < 200) //if pieces are less than 200, multiply by .50
                    Paid = Pieces * .50;
                else if (Pieces < 400)  //mulitply by .55 if less than 400
                    Paid = Pieces * .55;
                else if (Pieces < 600) // multiply by .60 if less than 600
                    Paid = Pieces * .60;
                else  // multiply by .65 if everything else doesnt apply 
                    Paid = Pieces * .65;
            }

            public string Name;
            public int Pieces;
            public double Paid;

        }

        private void SummaryOutPut_TextChanged(object sender, EventArgs e)
        {

        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void helpToolStripMenuItem_Click_1(object sender, EventArgs e)
        {

        }

        /* the following lines of code are menu items*/
        private void aboutToolStripMenuItem_Click_1(object sender, EventArgs e)
        {   //MSG box that displays name of lab and my name when clicking about and help item.
            MessageBox.Show("Lab 5 by J Soto"); 
        }

        private void exitToolStripMenuItem_Click_1(object sender, EventArgs e)
        {    //exit menu item that closes the windows form. 
            this.Close(); 
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {    //menu item that clears the employee name and # of pieces text box.
            EmployeeNameTextBox.Clear();
            NumOfPiecesText.Clear();
        }

        private void clearAllToolStripMenuItem_Click(object sender, EventArgs e)
        {    //menu item to clear all the text boxes.
            EmployeeNameTextBox.Clear();
            NumOfPiecesText.Clear();
            SummaryOutPut.Clear(); 
        }

        private void fontToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void colorToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void calculatePayToolStripMenuItem_Click(object sender, EventArgs e)
        {  //does the calculations 
            string name = (EmployeeNameTextBox).Text;
            int pieces = Convert.ToInt32(NumOfPiecesText.Text);

            if (name == "")
                MessageBox.Show("You must enter a name.");
            else if (pieces < 1 || pieces > 799)
                MessageBox.Show("Enter a number between 1 and 799.");
            else
            {
                MyData data = new MyData(name, pieces);
                MyList.Add(data);

                MessageBox.Show(string.Format("Amount Earned: {0:C}", data.Paid));

            }
        } 

        private void summaryToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Syntax_Error
  • 101
  • 1
  • 2
  • 10
  • Welcome to StackOverflow. Please [edit] your question and change the title to something that will be useful to future readers of this site. "Having trouble with my C# assignment" has no useful content to be found in a search (or when simply browsing the list of questions here) that explains anything about the question. Also, you can narrow down the problem by setting a breakpoint on the first line in your problem event handler and then stepping through the code when you click the button. It will tell you what object is a null reference. – Ken White Oct 05 '13 at 23:49
  • Welcome to Stack Overflow! Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Oct 06 '13 at 00:18

2 Answers2

3

Ah, I remember the days of not understanding null reference exceptions. Rather than give you the answer outright it's better to tell you how to diagnose the problem.

Your exception occurs when you click the button that calls summaryButton_Click. You know that the error occurs in that block of code. Null reference means that one of your variables is null (has no value assigned to it).

To find that value place break points on each line inside your summaryButton_Click function, run the program and click the button. You'll then be able to see which line of code throws the error. I think you'll find it's the name variable and the pieces variable haven't been assigned values.

Daniel Lane
  • 2,575
  • 2
  • 18
  • 33
  • Surely in any IDE that you can place breakpoints (with C# its usually visual studio) you can just tell it to break on an exception? – Chris Oct 06 '13 at 00:08
1

Get in the habit of referencing class-level variables using the this keyword. It let's other programmers who are reading your code know that the variable doesn't exist somewhere in the method scope.

As for your null reference exception, pieces hasn't been initialized yet when you try to reference its value in summaryButton_Click(). You're probably getting confused because of all the name colliding with your local and class-level variables.

Now for some other errors I can see:

total_Pay isn't initialized either in summaryButton_Click(). Remember, when you try to reference memory that isn't there, you will get a null reference exception.

Also, for some reason you have nested a few classes in another class. By looking at the code you posted, I can tell you there is no reason for doing this. Take some time cleaning up your code. You will find that readable code is much easier to understand.

Rohan
  • 359
  • 2
  • 16
  • I will agree that there is confusion between the `pieces` field and the fact that `pieces` is being used as a local variable in a few places but I wouldn't agree that you should use `this` whenever you use class-level variables - its a matter of code style and I personally haven't come across code that always uses this for class-level variables. Also there are reasons for embedding classes in other classes. Otherwise why would the feature exist? Generally its if a class is directly tied to another class like here where it is a data class that may only be relevant to this class. – Chris Oct 06 '13 at 00:14
  • @Chris, I meant that I don't see any reason for him implementing nested classes __in this case__. The way I wrote it made it sound as if one shouldn't use it in any case. I apologize for this. – Rohan Oct 06 '13 at 00:21
  • If the data class is not used outside of this class then why wouldn't you make it a nested class? Of course we can't tell whether it is being used externally without seeing any more code. Its certainly something for the OP to think about though and make up his mind on though. :) – Chris Oct 06 '13 at 00:24
  • @Chris, I assumed it was used externally because the `Data` class is public. If it wasn't meant to be used externally, it would be private. But, you're right, I should have made the statement only after seeing more of the OP's code :). – Rohan Oct 06 '13 at 00:31
  • Oh yeah, fair play then. :) – Chris Oct 06 '13 at 00:32
  • thank you for the feedback. I fixed the null exception, but I can't seem to figure out how to find the average pay for all employees. – Syntax_Error Oct 07 '13 at 18:35