【发布时间】: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 -
chkAll或chk是null.. 这是因为您对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