如何引用动态生成的CheckBoxList?(思归等达人求救,抓狂几天了)
//代码如下,我知道错误的原因,就是没有办法解决
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ int i=0;
CheckBoxList cbl = new CheckBoxList();
cbl.ID = "cbl1 ";
cbl.RepeatDirection = RepeatDirection.Horizontal;
cbl.Items .Add (new ListItem (i.ToString ()));
cbl.Items.Add(new ListItem(i.ToString()));
cbl.Items.Add(new ListItem(i.ToString()));
form1.Controls.Add(cbl);
i++;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CheckBoxList cbl = new CheckBoxList();
cbl = (CheckBoxList)form1.FindControl( "cbl1 ");/*无法用此引用到该控件*/
ViewState[ "cblInfo "] = cbl.SelectedItem.Text;/*这里就出错误了,因为使用了null引用(空引用)infamous Error!!!*/
Response .Write (ViewState [ "cblInfo "].ToString ());
}
------解决方案--------------------我不是达人,只好路过了
------解决方案--------------------动态创建的不能保存状态,使用
Request.Form[ "cbl1 "]得到
------解决方案--------------------可以先在html界面中定义空的CheckBoxList,然后在page_load事件中动态添加item,这样就可以在Button1_Click事件中取到这个CheckBoxList
------解决方案--------------------声明上面试试
public CheckBoxList cbl;