【问题标题】:NullReference exception thrown during if statement, what's wrong? [duplicate]在 if 语句中抛出 NullReference 异常,这是怎么回事? [复制]
【发布时间】:2014-05-08 22:29:38
【问题描述】:

我正在尝试实现一个函数来检索已检查的记录,然后该函数将它们添加到 ArrayList,然后将 ArrayList 保存到 ViewState。本质上,有一个按钮可以从表中删除(通过复选框)选择的行。所以在 Page_Load 事件之后,我单击按钮删除选定的行,但我得到一个空引用异常:

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

提前致谢

【问题讨论】:

  • Use the debugger - chkAllchknull.. 这是因为您对 FindControl 的调用没有返回您期望的结果。
  • 在调试器中运行,哪个变量为空?
  • 我猜grdUnsubscribe 是一个 GridView,chkAll 是它的某一行或页眉/页脚。您需要使用GridViewRow.FindControl("chkAll"),因为该行是 NamingContainer 而不是 GridView。如果它在标题中,您可以使用grdUnsubscribe.HeaderRow.FindControl...
  • 我很想说:Jon Skeet 说,但这次 Marc Gravell 说:don't use arraylist 开头:)跨度>
  • 将 ArrayList 烧毁,这不再是 C# 1.0!

标签: c# asp.net if-statement webforms nullreferenceexception


【解决方案1】:

如果没有更多有关异常的详细信息,很难说哪个变量为空,一个好的起点是查看引发异常的行。

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

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

那么问题是 ViewState 为空。

【讨论】:

    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多