求助

woiyyyy 2008-12-15 02:28:53
 protected void Button1_Click(object sender, EventArgs e)
{
string buystr = "";

for (int i = 0; i < 2; i++)
{
CheckBox chk = (CheckBox)FindControl("CheckBox" + i.ToString());
//CheckBox chk = (CheckBox)DataList1.Items[i].FindControl("CheckBox1");

if (chk.Checked)//这一行老是提示 未将对象引用设置到对象的实例。是没获取到CheckBox控件吗?

{
string id = chk.Text;
buystr = buystr + id + ",";
Response.Write("<script>alert('"+buystr+"');</script>");
}
}
if (buystr == "")
{
Response.Write("<script>alert('未选择任何选项!');</script>");
}
else
{
Response.Write("<script>alert('" + buystr + "');</script>");
//Session["strbuy"] = buystr;
//Response.Redirect("Shopping.aspx");
}

}



麻烦大家帮忙看看有什么问题? 没获取到CheckBox控件吗?
...全文
56 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
woiyyyy 2008-12-15
  • 打赏
  • 举报
回复
非常感谢!
woiyyyy 2008-12-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 zgke 的回复:]

FindControl 如果找不到返回为null
if(chk==null)
{
....
}


可能你的chk在其他控件里
[/Quote]
chk没在其他控件里,就在Form 里的
CheckBox chk = (CheckBox)FindControl("CheckBox" + i.ToString());
heyu1000 2008-12-15
  • 打赏
  • 举报
回复
你是在一个用户控件里面有CheckBox控件吧,首先你得确认是否真的在客户端显示的时候有checkbox1这样名字的控件,没有的话肯定获取不到的,用户控件里面的CheckBox在客户端显示不是这样的名字。
程序里面最好判断一下,这样就不会出错。
CheckBox chk = FindControl("CheckBox" + i.ToString()) as CheckBox;
if(chk!=null && chk.Checked)
{
.........
}
zgke 2008-12-15
  • 打赏
  • 举报
回复

FindControl 如果找不到返回为null
if(chk==null)
{
....
}


可能你的chk在其他控件里

111,131

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧