Reputation: 7537
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?
Upvotes: 0
Views: 1466
Reputation: 7537
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.
Upvotes: 1
Reputation: 453
Your async trigger must be inside the update panel. It may not be finding it because it is not inside of the update panel. Furthermore, because you are doing an async postback, only what is inisde of the update panel will get refreshed; thus you are in essence "reseting" Label 1.
This is why your code behind cannot find Label 1. Do this:
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
<asp:Label ID="Label3" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="Label2" runat="server"></asp:Label>
</form>
This will help you to see. The labels 1 and 3 will always get updated now, but since label 2 is outside of the update panel, it will not because the Page doesn't see this on postback.
Code Behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label3.Text = "label 3";
Label2.Text = "label 2";
Label1.Text = "label 1";
}
The result:
Upvotes: 1