0
        XmlDocument studentData;
        XmlNodeList studentList;
        TotalClass totalClass = null;
        string gender = "";

        studentData = new XmlDocument();
                studentData.LoadXml("<root>"
                    + "<STUDNT ID=\"7\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"16\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"22\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"25\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"27\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"32\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"35\" Gender=\"f\"></STUDNT>"
                    + "<STUDNT ID=\"45\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"4423453244\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"44344\" Gender=\"F\"></STUDNT>"
                    + "</root>");

        studentList = studentData.SelectNodes("//STUDENT");
        if(studentList != null && studentList.Count > 0)
        {
            foreach(XmlElement student in studentList)
            {
                gender = student.GetAttribute("Gender");
                switch(gender)
                {
                    case "F":
                        totalClass.Females++;   
                        break;

                    default:
                    case "M":
                        totalClass.Males++;                           
                        break;
                }

            }// end loop


        }

        this.lblMales.Text = totalClass.Males.ToString ();      
        this.lblFemale.Text = totalClass.Females.ToString();
        this.lblTotal.Text = (totalClass.Females + totalClass.Males).ToString();

I need some help with this progoram. I was assigned to debug this program, and I unable to find a way to solve. Keep getting the NullReferenceException when clicked the count button.

mybirthname
  • 17,949
  • 3
  • 31
  • 55
Duke
  • 23
  • 5
  • 4
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mybirthname Oct 08 '16 at 09:01

2 Answers2

0

Your totalClass object is null. Before your foreach, declare your class. You can do it with default.

studentList = studentData.SelectNodes("//STUDENT");
totalClass = new TotalClass();//add this.

Read this question, it is pretty much the famous question for C# in stack overflow: What is a NullReferenceException, and how do I fix it?

Community
  • 1
  • 1
mybirthname
  • 17,949
  • 3
  • 31
  • 55
0

try to modify like this

studentList = studentData.SelectNodes("/root/STUDNT");

and modify to

totalClass = new TotalClass();

Esperento57
  • 16,521
  • 3
  • 39
  • 45