Search code examples
c#asp.netviewstateasp.net-4.0

Adding and maintaining Table Rows and Cells to an ASP.net table


I have an ASP.net table, and I am adding Tables rows and cells to it dynamically at run time, and also adding controls (text boxes and labels) to these cells. I am creating and filling these controls at the OnInit event, on hope that they will be automatically saved into view sate. But they are not! on each postback the table is reset and appears empty.

I read many solutions like to save the controls in Cache or in Session or manually add them to view sate and manually save their values to view state, but I want a straighforward solution. Like when u drag drop any asp.net component, and you forget about maintaining its state.

Thanks


Solution

  • As tranceporter suggested, you will have to add table control everytime. However, if you want to maintain viewstate between post backs then you need to rebuild the table in the PreInit event, e.g.

    protected void Page_PreInit(object sender, EventArgs e)
    {
        TableRow row = new TableRow();
        TableCell cell = new TableCell();
        cell.Controls.Add(new TextBox());
        row.Cells.Add(cell);
        table.Rows.Add(row);
    }
    

    If the control is created in the PreInit event then the ASP.NET framework will apply the viewstate to the controls for you before the page Init and Load events fire. See here for more details on the ASP.NET page life cycle:

    http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx