views:

88

answers:

2

Hi everyone,

I have a very weird issue. I have a UserControl that has some controls inside. I want to refer those controls after, in another postback. But when I try to get them the Controls property of my controls returns null. I'm working on vs2008.

Here is the sample code:

public partial class MyUserControl : System.Web.UI.UserControl, INamingContainer
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (Control control in this.Controls)
        {
            Response.Write(control.ClientID);
        }
    }

    private void MyTable()
    {
        Table table = new Table();
        TableRow row = new TableRow();
        TableCell cell = new TableCell();

        CheckBox check = new CheckBox();
        check.ID = "theId";
        check.Text = "My Check";
        check.AutoPostBack = true;
        cell.Controls.Add(check);
        row.Cells.Add(cell);

        check = new CheckBox();
        check.ID = "theOther";
        check.AutoPostBack = true;
        check.Text = "My Other Check";

        cell = new TableCell();
        cell.Controls.Add(check);
        row.Cells.Add(cell);

        table.Rows.Add(row);
        this.Controls.Add(table);
    }

    protected override void Render(HtmlTextWriter writer)
    {
        MyTable();
        base.Render(writer);
    }
}

and the Default.aspx page is something like:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.cs" Inherits="Tester.Default" %>
<%@ Register TagPrefix="uc1" TagName="MyControl" Src="~/MyUserControl.ascx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Unbenannte Seite</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:MyControl ID="MyControlInstance" runat="server" />
    </div>
    </form>
</body>
</html>

I don't know if I'm lost in some part of the ASP.NET life cycle. But this situation is making me crazy. Any help would be very grateful.

+4  A: 

Create your child controls (MyTable) in either CreateChildControls or OnInit:

protected override void CreateChildControls()
{
    MyTable();
    base.CreateChildControls();
}

Or

protected override void OnInit(object sender, EventArgs e) 
{
    MyTable();
    base.OnInit(e);
}

You shouldn't/cannot create controls in Render as it occurs after Page_Load. See the ASP.Net Page Lifecycle here.

GenericTypeTea
You´re right. Now I want to ask you. The Table should be created everytime the page does postbacks? or there is a way to keep it in memory to handle it later.
Lug
You should recreate it every time.
GenericTypeTea
A: 

I believe it is because the Render event occurs after Page_Load, so when you are trying to iterate your control collection, it hasn't been set up yet. Most common solution is to override CreateChildControls to get the proper timing down.

KP