0

Here is my code, on line 144

peopleEntering.Add(new PersonEntered(personName, dateEntered, doorTypeEnum));

is where I get The error: object reference not set to an instance of an object. WHY?

  protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.PostedFile.FileName == string.Empty)
        {

            return;
        }
        else
        {
            string[] FileExt = FileUpload1.FileName.Split('.');
            string FileEx = FileExt[FileExt.Length - 1];
            if (FileEx.ToLower() == "csv")
            {
                FileUpload1.SaveAs(Server.MapPath(" " + FileUpload1.FileName));
            }
            else
            {

                return;
            }
        }
        CSVReader reader = new CSVReader(FileUpload1.PostedFile.InputStream);
        string[] headers = reader.GetCSVLine();
        DataTable dt = new DataTable();

        foreach (string strHeader in headers)
            dt.Columns.Add(strHeader);
        string[] data;
        while ((data = reader.GetCSVLine()) != null)
            dt.Rows.Add(data);
        foreach (DataRow row in dt.Rows)
        {
            string dateAndTime = row["Date and Time"].ToString();
            string personName = row["Description #2"].ToString();
            string doorType = row["Card number"].ToString();

            DateTime dateEntered = Convert.ToDateTime(dateAndTime);
            DoorType doorTypeEnum;

            bool personExists = false;
            foreach (object name in listboxOfNames.Items)
            {
                if (name.ToString() == personName)
                {
                    personExists = true;
                    break;
                }
            }
            if (!personExists)
            {
                listboxOfNames.Items.Add(personName);

            }
            switch (doorType)
            {
                case "A02 - Rear Entrance":
                    doorTypeEnum = DoorType.RearEntranceDoor;
                    break;
                case "B12 - Exterior Main Floor Man Trap":
                    doorTypeEnum = DoorType.ExteriorMainFloorDoor;
                    break;
                case "B12 - Interior Main Floor Man Trap":
                    doorTypeEnum = DoorType.InteriorMainFloorDoor;
                    break;
                case "C13 - Rear Break Room Door":
                    doorTypeEnum = DoorType.RearBreakRoomDoor;
                    break;
                case "B02 - Exterior Basement Man Trap":
                    doorTypeEnum = DoorType.ExteriorBasementDoor;
                    break;
                case "B02 - Interior Basement Man Trap":
                    doorTypeEnum = DoorType.InteriorBasementDoor;
                    break;
                case "D01 - Managed Services Main door":
                    doorTypeEnum = DoorType.ManagedServicesDoor;
                    break;
                case "D01 - Managed Services Big Door":
                    doorTypeEnum = DoorType.ManagedServicesBigDoor;
                    break;
                default:
                    doorTypeEnum = DoorType.None;
                    break;
            }
            peopleEntering.Add(new PersonEntered(personName, dateEntered, doorTypeEnum));
        }


        for (int i = 0; i < peopleEntering.Count; i++)
        {
            DateTime startDate = new DateTime();
            DateTime endDate = new DateTime();
            string personName = peopleEntering[i].PersonName;
            if ( peopleEntering[i].DoorEntered == DoorType.RearEntranceDoor)
            {
                startDate = peopleEntering[i].DateOfEntry;
                for ( int j = i + 1; j < peopleEntering.Count; j++)
                {
                    if (peopleEntering[j].DoorEntered == DoorType.ExteriorBasementDoor && peopleEntering[j].PersonName == personName)
                    {
                        endDate = peopleEntering[j].DateOfEntry;
                    }
                }

            }
            workSpans.Add(new WorkSpan(personName, startDate, endDate));

        }

        csvReaderGv.DataSource = dt.Rows;
        csvReaderGv.DataBind();
    }




            }   
Jay
  • 41
  • 8
  • 2
    Please avoid posting your whole source code; post only relevant lines. And null reference exceptions are all the same... Just go in with a debugger and check why your object is null. `peopleEntering` is probably not initialized or set to null explicitly before that line, don't have the time to read _all_ that code. – Pierre-Luc Pineault Aug 20 '13 at 21:23
  • Did you make sure to instantiate peopleEntering? It seems like this may be the case. – Mani5556 Aug 20 '13 at 21:24
  • 2
    You haven't shown the declaration or initialization of `peopleEntering`. I suspect you never give it a non-null value. – Jon Skeet Aug 20 '13 at 21:24
  • @Mani5556: I think you mean initialize rather than instantiate. – Jon Skeet Aug 20 '13 at 21:25
  • Looks like `peopleEntering` is `null`, but you didn't give us enough info to debug that. Open up Visual Studio, set a breakpoint, verify that `peopleEntering` is null, then trace back and understand why it's not being initialized properly. – jason Aug 20 '13 at 21:26
  • You have lost me, please give a example. – Jay Aug 20 '13 at 21:27
  • possible duplicate of [What is a NullReferenceException in .NET and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net-and-how-do-i-fix-it) – Henk Holterman Aug 20 '13 at 21:31

2 Answers2

4

On that particular line the only possible source of a NullReferenceException is if peopleEntering is null. Everything else in that statement is a new expression or a local / field read. Looking at the posted method it appears this is a field vs. a local in the method. Did you remember to initialize it to a non-null value (assuming type is List<PersonEntered>)

private List<PersonEntered> peopleEntering = new List<PersonEntered>();
Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
JaredPar
  • 673,544
  • 139
  • 1,186
  • 1,421
  • The error could also come from the `PersonEntered` constructor; if it is marked with `[DebuggerNonUserCode]` or `[DebuggerStepThrough]` (not sure which at the moment), then the debugger would not stop inside the constructor, but at the call site, i.e. on that line. – stakx - no longer contributing Aug 20 '13 at 21:30
  • @stakx that is very true. I was taking the OP on their word that this is where the exception actually occurred though. – JaredPar Aug 20 '13 at 21:33
  • 1
    @Jay, [just mark the answer that helped you the most as Accepted](http://stackoverflow.com/help/someone-answers), if you solved your own problem [you can post your own answer to the question and mark that instead](http://stackoverflow.com/help/self-answer). – Scott Chamberlain Aug 20 '13 at 21:40
1

Just a guess since you are using ASP.NET (as seen in your prev. question):

I assume that you have initialized the List once, maybe with the IsPostBack check.

private List<PersonEntered> peopleEntering;

protected void Page_Load(Object sender, EventArgs e)
{
    if(!IsPostBack)
    {
         peopleEntering = GetPeropleEntering(); // a method that retrieves them from database
    }
}

In this case you either have to reload the list on every postback(remove the IsPostBack check) or you have to store it somewhere to retain it's state across postbacks. Session is one way. Remember that all variables (incl. all controls) are disposed at the end of a page's life-cycle.

Here are 8 others: http://msdn.microsoft.com/en-us/magazine/cc300437.aspx

Community
  • 1
  • 1
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859