C# if语句期间引发的NullReference异常,what';怎么了?
我正在尝试实现一个函数,该函数检索已检查的记录,然后将它们添加到ArrayList,然后将ArrayList保存到ViewState。本质上,有一个按钮可以从表中删除选中的行(通过复选框)。因此,在Page_Load事件之后,我单击按钮删除所选行,但得到一个nullreference异常:C# if语句期间引发的NullReference异常,what';怎么了?,c#,asp.net,if-statement,webforms,nullreferenceexception,C#,Asp.net,If Statement,Webforms,Nullreferenceexception,我正在尝试实现一个函数,该函数检索已检查的记录,然后将它们添加到ArrayList,然后将ArrayList保存到ViewState。本质上,有一个按钮可以从表中删除选中的行(通过复选框)。因此,在Page_Load事件之后,我单击按钮删除所选行,但得到一个nullreference异常: An exception of type 'System.NullReferenceException' occurred but was not handled in user code Addi
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;
}
受保护的void GetSelectedRecords()
{
ArrayList-arr;
如果(ViewState[“SelectedRecords”]!=null)
arr=(ArrayList)视图状态[“SelectedRecords”];
其他的
arr=新的ArrayList();
复选框chkAll=新复选框();
chkAll=(复选框)grdUnsubscribe.FindControl(“chkAll”);
for(int i=0;i
提前感谢没有异常的更多细节很难说哪一个变量为空,最好从引发异常的行开始 例如,假设在此行引发异常:
if (ViewState["SelectedRecords"] != null)
然后问题是ViewState为null。-
chkAll
或chk
为null
。。这是因为对FindControl
的调用没有返回预期的结果。在调试器中运行它,哪个变量为null?我猜grdUnsubscribe
是一个GridView,而chkAll
位于它的某一行或页眉/页脚中。您需要使用GridViewRow.FindControl(“chkAll”)
,因为该行是命名容器,而不是GridView。如果它在标题中,你可以使用grdUnsubscribe.HeaderRow.FindControl…
。我很想说:Jon Skeet说,但这次Marc Gravell说:首先:)将ArrayList烧掉,这不再是C#1.0了!