简体   繁体   中英

Adding controls to a table control dynamically

I have one table control "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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