在if语句期间抛出NullReference异常,什么'错了

本文关键字:什么 错了 异常 NullReference 语句 if | 更新日期: 2023-09-27 18:02:23

我试图实现一个函数,检索已检查的记录,该函数然后将它们添加到ArrayList,然后将ArrayList保存到ViewState。实际上,有一个按钮可以删除表中选中的行(通过复选框)。Page_Load事件后,我点击按钮删除选中的行但得到nullreference异常

An exception of type 'System.NullReferenceException' occurred 
    but was not handled in user code
Additional information: Object reference not set to an instance of an object.

函数如下:

protected void GetSelectedRecords()
{
    ArrayList arr;
    if (ViewState["SelectedRecords"] != null)
        arr = (ArrayList)ViewState["SelectedRecords"];

    else
        arr = new ArrayList();

    CheckBox chkAll = new CheckBox();
    chkAll = (CheckBox)grdUnsubscribe.FindControl("chkAll");


    for (int i = 0; i < grdUnsubscribe.Rows.Count; i++)
    {
        if (chkAll.Checked == true)
        {
            if (!arr.Contains(grdUnsubscribe.DataKeys[i].Value))
            {
                arr.Add(grdUnsubscribe.DataKeys[i].Value);
            }
        }
        else
        {
            CheckBox chk = (CheckBox)grdUnsubscribe.Rows[i].Cells[0].FindControl("chk");
            if (chk.Checked)
            {
                if (!arr.Contains(grdUnsubscribe.DataKeys[i].Value))
                {
                    arr.Add(grdUnsubscribe.DataKeys[i].Value);
                }
            }
            else
            {
                if (arr.Contains(grdUnsubscribe.DataKeys[i].Value))
                {
                    arr.Remove(grdUnsubscribe.DataKeys[i].Value);
                }
            }
        }
    }
    ViewState["SelectedRecords"] = arr;
}

Thanks in advance

在if语句期间抛出NullReference异常,什么'错了

如果没有关于异常的更多细节,就很难判断哪个变量为null,最好从抛出异常的那一行开始。

例如,假设在这一行抛出异常:

if (ViewState["SelectedRecords"] != null)

那么问题是ViewState是null