简体   繁体   中英

Error 'Object reference not set to an instance of an object.'

Does anyone know where is my code going wrong here? This piece of code work perfectly fine but I transferred the file to another computer, this error popped out when I compile the file.

 private void ShowGeneratedSchedule(string sLocationName, string sAllocationDate)
    {
        //lstAllocation = db.allocations.Where(a => a.AllocationDate == sAllocationDate &&
        //    a.LocationName == sLocationName).ToList();

        scheduleDGV.EditMode = DataGridViewEditMode.EditProgrammatically;
        for (int i = 0; i < lstAllocation.Count; i++)
        {
            for (int j = 0; j < scheduleDGV.Rows.Count - 1; j++)
            {
                for (int k = 0; k < scheduleDGV.Columns.Count; k++)
                {
                    if (scheduleDGV[0, j].Value.Equals(lstAllocation[i].LocationName) &&
                        scheduleDGV[1, j].Value.Equals(lstAllocation[i].StationName) &&
                        scheduleDGV.Columns[k].HeaderText.Equals(lstAllocation[i].AllocationTime.ToString()))
                    {
                        if (lstAllocation[i].EmployeeName != null)
                        {
                            scheduleDGV[k, j].Value = lstAllocation[i].EmployeeName;
                        }
                    }
                }
            }
        }

        //scheduleDGV.DataSource = lstEmployeeSlot;
    }

The error is displayed when it reaches this line,

for (int i = 0; i < lstAllocation.Count; i++)

Does anyone know what's wrong here? Is it possible that it is transferred into another computer?

This, most likely, means that lstAllocation is null and was never assigned a value. Why this line is commented out?

 //lstAllocation = db.allocations.Where(a => a.AllocationDate == sAllocationDate &&
        //    a.LocationName == sLocationName).ToList();

lstAllocation is not initialized? What is it with the comment in the first line of the method? Why is that commented out? Without that lstAllocation has no content.

Looks like you have the line commented out where you assign lstAllocation to something. This is most likely your problem.

The lstAllocation reference variable is initialized with null (or an object is not constructed yet or an object is missing ) somewhere within the program/code.

It will be good practice to check the value of reference variable - whether it has null or reference of an object.

private void ShowGeneratedSchedule(string sLocationName, string sAllocationDate)
    {
        if(lstAllocation==null){
           Console.WriteLine("List is not initialized. Can't proceed");
           return;
        }
        //rest code
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM