繁体   English   中英

错误“对象引用未设置为对象的实例。”

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

有人知道我的代码在哪里出错吗? 这段代码工作得很好,但是我将文件传输到另一台计算机上,当我编译文件时会弹出此错误。

 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;
    }

到达此行时显示错误,

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

有人知道这是怎么回事吗? 是否有可能将其转移到另一台计算机上?

这很可能意味着lstAllocation为null,并且从未分配值。 为什么此行被注释掉?

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

lstAllocation是否未初始化? 方法第一行中的注释是什么? 为什么将其注释掉? 没有那个lstAllocation就没有内容。

看起来您已经注释了该行,在其中将lstAllocation分配给某些内容。 这很可能是您的问题。

lstAllocation参考变量在程序/代码内的某处用null初始化(或尚未构造对象或缺少对象)。

最好检查引用变量的 -它是否为null或对象的reference

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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