R – Control scope within Repeater, with and without UpdatePanel

asp.netrepeaterscopeupdatepanel

Why does the following give me a compilation error for line B (Label2, outside UpdatePanel) but not for line A (Label1, inside UpdatePanel)? I would have expected both lines to give an error since both controls are within the same Repeater and should therefore not be directly accessible outside the repeater, since there is no one unique instance.

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = Label1.ClientID;  // Line A - compiles fine
        Label2.Text = Label2.ClientID;  // Line B - "The name 'Label2' does not exist in the current context"
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:Repeater runat="server" ID="Repeater1">
                <ItemTemplate>
                    <asp:UpdatePanel runat="server" ID="UpdatePanel1">
                        <ContentTemplate>
                            <asp:Label ID="Label1" runat="server" Text="Label1" />
                        </ContentTemplate>
                    </asp:UpdatePanel>
                    <asp:Label ID="Label2" runat="server" Text="Label2" />
                </ItemTemplate>
            </asp:Repeater>
        </div>
    </form>
</body>
</html>

Best Answer

I'm betting if you comment out line B you'll get a run-time error on execution. Label1 is going to be a null reference.

When you create controls in the ASPX page Visual Studio tries to help you out by adding the controls to the code behind in the designer file which extends the class for the page. In this case it's adding one when it shouldn't be.

Short answer is it's a bug. You should submit it but it shouldn't be a blocking issue.

Related Topic