Search code examples
c#asp.netajaxupdatepanel

UpdatePanel controls unavailable - Object reference not set to an instance of an object


I have an UpdatePanel with a Label control, Label1, and a button outside it, Button1, and another Label control outside the UpdatePanel, Label2. When the button is clicked, I want the Label text to be updated in Label1:

ASPX page

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" AsyncPostBackTimeout="0" />
    <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
        </Triggers>
        <asp:ContentTemplate>
            <asp:Label ID="Label1" runat="server"></asp:Label>
        </asp:ContentTemplate>
    </asp:UpdatePanel>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
    <asp:Label ID="Label2" runat="server"></asp:Label>
</form>

Code-Behind

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
    Label2.Text = "some text";
    Label1.Text = "some text";
}

This should be straight-forward - I should be able to update the Label1 text with a button click event. The Label2 line succeeds (it obviously won't appear without a page postback, though), where the Label1 line fails with "Object reference is not an instance of an object". Why is Label1 null, when it is right there on the page, just that it is inside an UpdatePanel? How am I supposed to instantiate controls that should already be on the page and accessible, just like Label2 is?


Solution

  • Code has <asp:ContentTemplate> and </asp:ContentTemplate> instead of <ContentTemplate> and </ContentTemplate> tags in the UpdatePanel. I corrected this and it works now. The controls became out of scope since the code couldn't find the real ContentTemplate or anything in it.