ASP.NET 后台设置循环动态生成的LABEL控件的ID, 后台要获取的时候前台已变

//动态生成LABEL
for(int i=0;i<10;i++)
{
Label lb = new Label();
lb.Text = "123";
lb.ID = "lb"+i;
}

//取值时
for(int i=0;i<10;i++)
{
string str = ((Label)(this.FindControl("lb")+i)).Text;
........
}

由于使用母版页,前台ID已变。
后台应该怎么获取?

你这个查找控件的代码有点问题啊。

//取值时
for(int i=0;i<10;i++)
{
string str = (Label)(this.FindControl("lb"+i.ToString())).Text;
........
}

追问

问题不出在这儿,
后台设置LB.ID="lb"+i时,前台默认显示的标签ID变为"ct100_ContentPlaceHolderID_lb0",加了母版页的ID。。所以取不到前台的控件。

难道我要去掉母版页里面的ID?

追答

如果你是在C#代码中找id,不用那么麻烦,你用我贴上去的代码试一下。你的代码FindControl("lb"),是根据ID=“lb”找控件,并没有把i加上去。

如果你是在客户端找控件,就用这种方式。

追问

是后台取,我的代码里已经加了i, 我试过你的代码出错和我的一样。。取不到控件。。。

追答

你动态生成的Lable,有没有添加入当前的Page页面?

从你贴出的代码中,我并没有看到把Lable添加入当前页面的代码。

追问

第一次贴的只是部分代码。源码中已加入前台PANEL, 下面为前天生成的源码。ID已变

追答

你好。今天测试一下代码,发现我之前的回答基本都没帮上你什么,实在抱歉。


下面两种情况,希望可以解决你遇到的问题。

控件添加后,立刻使用(注:期间没有发生任何回传)

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //添加控件

            lbl.ID = "lbl";
            this.Page.Form.FindControl("ContentPlaceHolder1").Controls.Add(lbl);
            
            //查找控件
            Label lblT = this.Page.Form.FindControl("ContentPlaceHolder1").FindControl("lbl") as Label;
        }
    }
    
    
第二种情况(添加控件后,会有回传),需要重写OnInit()事件
    protected void btn_Click(object sender, EventArgs e)
    {
        Label lbl = this.Page.Form.FindControl("ContentPlaceHolder1").FindControl("lbl") as Label;
        lbl.Text = "123";
    }
    
    protected override void OnInit(EventArgs e)
    {
        Label lbl = new Label();
        lbl.ID = "lbl";
        this.Page.Form.FindControl("ContentPlaceHolder1").Controls.Add(lbl);

        base.OnInit(e);
    }

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答