2 Replies - 1221 Views - Last Post: 08 May 2013 - 08:04 PM Rate Topic: -----

#1 a100cent  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 08-May 13

Please Help me I am getting a Null Reference Exception

Posted 08 May 2013 - 06:28 PM

 while (requiredClassesArrayCS[requiredCount].ToString() != classesArray[classesCount, 1].ToString())  
 while (requiredClassesArrayCS[requiredCount].ToString() != classesArray[classesCount, 1].ToString())
                {
                    // exits the loop if all rows of classesArray have been iterated
                    if (classesCount >= classesArray.GetUpperBound(0))
                        break;

                    // iterartes through each row of classes array
                    classesCount++;
                }

                // sets flag = 1
                if (requiredClassesArrayCS[requiredCount].ToString() == classesArray[classesCount, 3].ToString())
                    classesArray[classesCount, 7] = 1;

                // increment count
                requiredCount++;

                if (requiredCount >= requiredClassesArrayCS.Length)
                    break;
            } // end while


I am getting a null reference exception when I try to generate the schedule for this code. ( up above is the code I am getting error.

Below is my entire code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel; // use for Marshal.

namespace Example
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //*******************************************************************************
            //* This creates a schedule for a CS transfer student that ignores classes that *
            //* they have already received credit for by changing all the selected classes' *
            //* flags to 1.                                                                 *
            //*******************************************************************************

            // create a array to accept checked values from checkedListBox1
            object[] requiredClassesArrayCS = checkedListBox1.CheckedItems.OfType<object>().ToArray();

            // THIS CODE IMPORTS DATA FROM EXCEL INTO A 2-DIM ARRAY ***************************************************

            // This opens my existing Workbook for CSClasses
            Excel.Application excelApp = new Excel.Application();
            // uncomment next line if you want to see the excel application
            // excelApp.Visible = true;
            // set filepath
            string workbookPath = 
                "C:/Users/a100cent/Desktop/NewStudentTemplateCS.xlsx";
            // open workbook
            Excel.Workbook workbook = excelApp.Workbooks.Open(workbookPath,
                    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                    true, false, 0, true, false, false);

            // Get a reference to the first sheet of the workbook.
            Excel.Sheets excelSheets = workbook.Worksheets;
            string currentSheet = "Sheet1";
            Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

            // Take the used range of the sheet for the classes  and, get an object[,] array of all
            // of the cells in the range (their values).
            Excel.Range excelRange1 = (Excel.Range)excelWorksheet.get_Range("A2", "G44");
            // creates a 2-dim array and fills it with the selected range
            object[,] classesArray = (object[,])excelRange1.get_Value(
                Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);

            // This is working code that imports a 2-dim array from excel that shows when classes are
            // available according to TAMUT's STEM two year projected schedule. 
            // This was not implemented due to time resictions
            // To use this code uncomment, and add classesAvailabilityArray to ProcessObjects() method                
            // ----------------------------------------------------------------------------------------------
            // Take the used range of the sheet for the class availability and, get an object[,] array of all
            // of the cells in the range (their values).
            // Range excelRange2 = (Excel.Range)excelWorksheet.get_Range("A47", "G89");
            // object[,] classesAvailabilityArray = (object[,])excelRange2.get_Value(
            //    Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);

            // Clean up
            // Closes the workbook
            workbook.Close(false, workbookPath, null);
            Marshal.ReleaseComObject(workbook);

            // Closes the Excel Application
            Marshal.FinalReleaseComObject(excelApp.Workbooks);
            excelApp.Quit();
            Marshal.FinalReleaseComObject(excelApp);

            //*/ THIS CODE OPENS THE EXCEL FILE THAT YOU'RE EXPORTING TO *******************************************

            // This opens my existing Workbook for NewStudentTemplateCS
            Excel.Application excelApp2 = new Excel.Application();
            excelApp2.Visible = true;
            string workbookPath2 = 
                "C:/Users/a100cent/Desktop/NewStudentTemplateCS.xlsx";
            Excel.Workbook workbook2 = excelApp2.Workbooks.Open(workbookPath2,
                    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                    true, false, 0, true, false, false);

            // Get a reference to the first sheet of the workbook.
             Worksheet ws = (Worksheet)excelApp2.ActiveSheet; 

            //****************************************************************************************************

            // Process the data in the array with a this method.
            ProcessObjects(requiredClassesArrayCS, classesArray, ws);

            //Console.ReadLine(); // HOLD FOR DEBUG PURPOSES###########################################

            //// THIS CODE CLOSES THE EXCEL FILE THAT YOU EXPORTED TO **********************************************

            //// Clean up
            //// Closes the workbook
            //workbook2.Close(false, workbookPath2, null);
            //Marshal.ReleaseComObject(workbook2);

            //// Closes the Excel Application
            //Marshal.FinalReleaseComObject(excelApp2.Workbooks);
            //excelApp2.Quit();
            //Marshal.FinalReleaseComObject(excelApp2);

        } // end button1_Click 

        private void ProcessObjects(object[] requiredClassesArrayCS,object[,] classesArray, Worksheet ws)
        {
            ProcessSelection(requiredClassesArrayCS, classesArray);
            //// This variable, semester, keeps track of which year it is (even or odd) and
            //// which semester it is (spring or fall) by controlling which column of the 
            //// classesAvailabilityArray is accessed.
            //// 3 = spring of an even year
            //// 4 = fall of an even year
            //// 5 = spring of an odd year
            //// 6 = fall of and odd year
            //int semester;

            // once classes are selected, they are copied to a temporary location
            // while they're waiting to be printed
            object[,] tempArray = new object[8, 3];

            // This stops the while loop once enough credit hours have been taken 
            // if a break condition has not been met first.
            // It must reach 123 hours for CS Degree .
            int hourCounter = 0;

            int iteration = 0;

            while (hourCounter < 123)
            {
                // this while loop copies some classes from classes array to tempArray
                // so they can be printed into the excel template
                //
                int classes = 0, hours = 0; // stops while loop if limit is reached
                int tempArrayRow = 0, tempArrayCol = 0; // used to select individual elements of tempArray
                int classesArrayRow = 1, classesArrayCol = 1; // used to select individual elements of classesArray

                while (classes < 6 && hours < 15)
                {
                // These loops check the status of the flag and stops at the first avaliable
                // class/row of classesArray where flag = 0. Both if statementes are needed because 
                // classesArray is type object. When you insert a breakpoint and step through the code 
                // one line at a time while debugging you can see that the column classesArray[ , 7] 
                // continuously changes from type int to type double (Although i'm not exactly sure 
                // why) during the casting process. When classesArray[ , 7] is type int, the first
                // if loop works, and when classesArray[ , 7] is type double, the second if loop works.
                Top1:
                    if (classesArray[classesArrayRow, 7] is int)
                    {
                        // converts object element to an int for the following "==" operator
                        int flag = Convert.ToInt32(classesArray[classesArrayRow, 7]);

                        while (flag == 1)
                        {
                            classesArrayRow++;
                            // exits the loop if all rows of classesArray have been copied
                            if (classesArrayRow >= classesArray.GetUpperBound(0) + 1)
                                goto Lower1;
                            goto Top1;
                        }
                    }

                Top2:
                    if (classesArray[classesArrayRow, 7] is double)
                    {
                        // converts object element to an int for the following "==" operator
                        double flag = Convert.ToDouble(classesArray[classesArrayRow, 7]);

                        while (flag == 1)
                        {
                            classesArrayRow++;
                            goto Top2;
                        }
                    }

                
                    // copies the call EX: "MATH 2313" from classesArray to tempArray
                    tempArray[tempArrayRow, tempArrayCol] = classesArray[classesArrayRow, classesArrayCol];
                    tempArrayCol++;
                    classesArrayCol += 2;
                    // copies the name EX: "Calculus I" from classesArray to tempArray
                    tempArray[tempArrayRow, tempArrayCol] = classesArray[classesArrayRow, classesArrayCol];
                    tempArrayCol++;
                    classesArrayCol++;
                    // Copies the hours EX: "3" from classesArray to tempArray
                    tempArray[tempArrayRow, tempArrayCol] = classesArray[classesArrayRow, classesArrayCol];

                    // increments classes, hours, and hourCounter for exit decision
                    classes += 1;
                    // converts object element to an int for the following "+=" operator
                    int numberOfHours = Convert.ToInt32(classesArray[classesArrayRow, classesArrayCol]);
                    // adds numberOfHours to the following varriable to increment loop exit decision
                    hours += numberOfHours;
                    hourCounter += numberOfHours;

                    // sets flag to one
                    classesArrayCol += 3;
                    classesArray[classesArrayRow, classesArrayCol] = 1;

                    //reset column varriables
                    classesArrayCol = 1;
                    tempArrayCol = 0;

                    // increments rows for both arrays
                    tempArrayRow++;
                    classesArrayRow++;

                Lower1:

                    // exits the loop if all rows of classesArray have been copied
                    if (classesArrayRow >= classesArray.GetUpperBound(0) + 1)
                        break;

                }// end while loop

                // print method that prints temp array and clears tempArray for next use
                PrintArray(tempArray, iteration, ws);

                // iterates iteration. This controls which semester (or range of the excel sheet) is
                // currently being printed/exported
                iteration++;

                if (iteration >= 8)
                    break;

            } // end while loop
        }

        private void ProcessSelection(object[] requiredClassesArrayCS,object[,] classesArray)
        {
            // Sets all the flags from the selected "Required Classes" equal to 1

            // checks to see if no classes are selected from "Required Classes"
            // if (requiredClassesArrayCS.Length == 0)
                //goto ElectiveClasses;

            // position holder for array
            int requiredCount = 0;

            while (requiredClassesArrayCS[requiredCount] != null)
            {
                // initializes and resets classesCount to one
                int classesCount = 1;

                // This series of ifs changes the follow strings to the class names used in classesArray
                if (requiredClassesArrayCS[requiredCount].ToString() == "Forms of Literature OR World Literature")
                    requiredClassesArrayCS[requiredCount] = "English Literature";
                else if (requiredClassesArrayCS[requiredCount].ToString() == "Principles of Macroeconomics OR World Regional Geography OR General Psychology OR Introductory Sociology")
                    requiredClassesArrayCS[requiredCount] = "Social Science";
                else if (requiredClassesArrayCS[requiredCount].ToString() == "Arts Appreciation OR Introduction to Theater OR Music Appreciation")
                    requiredClassesArrayCS[requiredCount] = "Fine Arts";

 while (requiredClassesArrayCS[requiredCount].ToString() != classesArray[classesCount, 1].ToString())
                {
                    // exits the loop if all rows of classesArray have been iterated
                    if (classesCount >= classesArray.GetUpperBound(0))
                        break;

                    // iterartes through each row of classes array
                    classesCount++;
                }

                // sets flag = 1
                if (requiredClassesArrayCS[requiredCount].ToString() == classesArray[classesCount, 3].ToString())
                    classesArray[classesCount, 7] = 1;

                // increment count
                requiredCount++;

                if (requiredCount >= requiredClassesArrayCS.Length)
                    break;
            } // end while

This post has been edited by modi123_1: 08 May 2013 - 06:31 PM
Reason for edit:: fixed botched code tags


Is This A Good Question/Topic? 0
  • +

Replies To: Please Help me I am getting a Null Reference Exception

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,652
  • Joined: 02-June 10

Re: Please Help me I am getting a Null Reference Exception

Posted 08 May 2013 - 06:58 PM

Null reference, is the first error covered in the tutorial "What does this error mean?" linked below. The volunteers here are not going to scrub through more than 300 lines of your code when you your self have not put forth any effort in learning or doing even the most basic of debugging. They don't work for you - they will assist when it looks like you've made at least some effort.


tlhIn`toq's FAQ list

Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute.

Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.


TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated Apr 2013
Spoiler



Was This Post Helpful? 0
  • +
  • -

#3 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3461
  • View blog
  • Posts: 10,669
  • Joined: 05-May 12

Re: Please Help me I am getting a Null Reference Exception

Posted 08 May 2013 - 08:04 PM

And seeing those goto's in the code makes me even less willing to dig around in that mess...
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1