简体   繁体   中英

Why does my HTML table row loses view state after dynamically adding rows to this table?

I have a simple HTML table like this:

<table id="table" runat="server">
    <tr>
        <td>
            <asp:Label runat="server" Text="Column1" />
        </td>
    </tr>
    <tr id="tr_someId" runat="server">
        <td>
            <asp:Label ID="lb_someId" runat="server" />
        </td>
    </tr>
</table>

On every request I add dynamic rows between ( rowIdx = 1 ) the existing rows like:

protected override void OnLoad( EventArgs e )
{
    base.OnLoad( e );

    if( !IsPostBack )
    {
        lb_someId.Text = "Some text";
    }

    int rowIdx = 1;

    foreach( ISomething something in GetSomethings() )
    {
        HtmlTableRow tr = new HtmlTableRow();
        tr.Cells.Add( CreateLabelCell( something ) );

        table.Rows.Insert( rowIdx++, tr );
    }
}

Now, I wonder, why my lb_someId-Label loses its text on a PostBack? I think it should not happen because it is a fixed control. It does not lose its text when I comment the table.Rows.Insert( rowIdx++, tr ); line out.

Thank you in advance!

The reason that the value of the label gets lost is because it is part of a table to which new rows are being added in the OnLoad event. At this point in the lifecycle dynamically added controls are not being tracked anymore. The table tracks its viewstate as a whole, including some info about the label. If the label was outside of the table, there wouldn't have been a problem. See MSDN: Understanding ASP.NET View State .

Move the code to OnInit .

protected override void OnInit(EventArgs e)
{   
    base.OnInit(e);

    if( !IsPostBack )
    {
        lb_someId.Text = "Some text";
    }

    int rowIdx = 1;

    foreach( ISomething something in GetSomethings() )
    {
        HtmlTableRow tr = new HtmlTableRow();
        tr.Cells.Add( CreateLabelCell( something ) );

        table.Rows.Insert( rowIdx++, tr );
    }
}

Alternativelly, only moving the foreach loop to OnInit would suffice.

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    if( !IsPostBack )
    {
        lb_someId.Text = "Some text";
    }
}

protected override void OnInit(EventArgs e)
{   
    base.OnInit(e);

    int rowIdx = 1;

    foreach( ISomething something in GetSomethings() )
    {
        HtmlTableRow tr = new HtmlTableRow();
        tr.Cells.Add( new HtmlTableCell { InnerText = something } );

        table.Rows.Insert( rowIdx++, tr );
    } 
}

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