简体   繁体   English

动态将控件添加到表控件

[英]Adding controls to a table control dynamically

I have one table control "table1" 我有一个表控件“ table1”

And added controls to it in click event of one button as : 并在一个按钮的单击事件中向其添加控件为:

protected void Button2_Click(object sender, EventArgs e)
{
    TableRow row;
    TableCell cell;
    for (int i = 0; i < 3; ++i)
    {
        TextBox txt = new TextBox();
        txt.Text = i.ToString();
        row = new TableRow();
        cell = new TableCell();
        cell.Controls.Add(txt);
        row.Controls.Add(cell);
        Table1.Controls.Add(row);
    }
}

but i cant retrieve this controls in click event of another button. 但我无法在另一个按钮的单击事件中检索此控件。 i think it is because of postback. 我认为是因为回发。

How can i prevent it? 我该如何预防呢?

When adding controls dynamically, if you want to access them on postback, you need to re-create them every time the page is loaded. 动态添加控件时,如果要在回发时访问它们,则每次页面加载时需要重新创建它们。

Adding them in the click handler of one button and expecting them to be there for the click handler of another button will not work, as they have not been re-created on the second postback. 将它们添加到一个按钮的单击处理程序中,并期望它们存在于另一个按钮的单击处理程序中,将无法正常工作,因为尚未在第二次回发中重新创建它们。

You need to understand the asp.net page life cycle and change the logic of your page to fit in with it. 您需要了解asp.net页面的生命周期,并更改页面的逻辑以适应它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM