未将对象引用设置到实例(代码贴出来,大家帮忙看一下,愁了好多天了,谢谢)
private void Page_Load(object sender, System.EventArgs e)
{
nCount= Request.QueryString[ "count "]!=null?Int32.Parse(Request.QueryString[ "count "]):4; //默认投票为4个选项
if(!Page.IsPostBack)
{
if(Request.QueryString[ "voteid "]==null) //新建投票题目
{
Binding_Init(nCount); //动态加载nCount个投票选项
vote_count.Text=nCount.ToString();
}
}
}
private void Binding_Init(int nCount)
{
for(int i=1;i <=nCount;i++) //加载nCount个投票选项(文本框+下拉列表)
{
Label lab = new Label();
lab.ID = "lb "+i.ToString();
lab.Text = "选项: "+i.ToString();
TextBox txt= new TextBox(); //投票选项内容
txt.ID = "txt "+i.ToString();
txt.Width=100;
DropDownList ddl_style = new DropDownList();//投票选项结果的柱状颜色
ddl_style.ID = "ddl "+i.ToString();
ddl_style.Items.Add(new ListItem( "红色 ", "red "));
ddl_style.Items.Add(new ListItem( "黑色 ", "black "));
TableRow tr= new TableRow();
TableCell tc= new TableCell();
tc.Controls.Add(lab);
tc.Controls.Add(txt);
tc.Controls.Add(ddl_style);
tr.Cells.Add(tc);
tabDemo.Rows.Add(tr);
}
}
.........................
...................(略)
...... //下面是提交按钮
private void Btn_OK_Click(object sender, System.EventArgs e)
{
HtmlForm Frmstep = (HtmlForm)this.Page.FindControl( "step ");
for(int i=1;i <=nCount;i++)
{
//下面这行报错:未将对象引用设置到实例
txt[i]=((TextBox)Frmstep.FindControl( "txt "+i.ToString())).Text;
ddl[i]=((DropDownList)Frmstep.FindControl( "ddl "+i.ToString())).SelectedValue;
vote.Add_Vote(classid,txt[i].ToString(),ddl[i].ToString());
}
Response.Write( " <script> alert( '添加成功! '); </script> ");
}
请问大家:为什么我用.FindControl( "txt "+i.ToString())会报错:未将对象引用设置到实例? 难道是无法 Find 到ID为 "txt "+i.ToString()的控件?
我“查看源文件”都有 ID=txt1, ID=txt2 ....的input控件的,
惆怅,困惑 无助...
各位,帮个忙看看吧,谢谢了!
[解决办法]
你在if(!Page.IsPostBack)
里动态加控件 postback 后当然无法找到控件
补课 lifecycle
http://www.cnblogs.com/webabcd/archive/2007/03/12/671400.html