Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controls inside a Usercontrol don't get initialized if it's in a Repeater

Tags:

c#

.net

asp.net

I have a situation where I'm using some markup in 2 places on a page, one of which is in a repeater. The one in the repeater is not initializing its child controls; they're staying null.

Default.aspx:

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="nestedcontroltest._Default" %>
<%@ Register TagPrefix="a" Namespace="nestedcontroltest" Assembly="nestedcontroltest" %>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <asp:Repeater runat="server" ID="rptLetters" OnItemDataBound="rptLetters_ItemDataBound">
            <ItemTemplate>
                <a:MyControl runat="server" ID="ctrlMyControl"/>
            </ItemTemplate>
        </asp:Repeater>
    </body>
</html>

Default.aspx.cs:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        rptLetters.DataSource = new[] { "a", "b", "c" };
        rptLetters.DataBind();
    }

    public void rptLetters_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        var ctrlMyControl = (MyControl)e.Item.FindControl("ctrlMyControl");
        ctrlMyControl.Text = e.Item.DataItem.ToString();
    }
}

MyControl.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="nestedcontroltest.MyControl" %>
<asp:Panel runat="server" ID="pnlContent">
    <asp:Literal runat="server" ID="ltlText"/>
</asp:Panel>

MyControl.ascx.cs:

public partial class MyControl : UserControl
{
    public string Text { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        ltlText.Text = Text;
    }
}

When I try to load this, I get "Object reference not set to an instance of an object." - apparently ltlText is null.

How can I get my UserControl to initialize properly?

like image 540
Chris Adams Avatar asked Jul 27 '12 06:07

Chris Adams


1 Answers

Found the answer:

  1. The repeater had nothing to do with the problem.
  2. In Default.aspx, I needed to register the control by name rather than by namespace.

    <%@ Register TagPrefix="a" Namespace="nestedcontroltest" Assembly="nestedcontroltest" %>
    

    Needs to be changed to

    <%@ Register TagPrefix="a" TagName="MyControl" Src="~/MyControl.ascx" %>
    

And then the control gets initialized properly, even when it's in the repeater. Perhaps a bug in ASP.net, or perhaps I needed to use the full assembly name? Regardless, thanks for all your help guys.

like image 63
Chris Adams Avatar answered Sep 21 '22 12:09

Chris Adams