msfanboy
msfanboy

Reputation: 5291

can not access control inside asp.net updatepanel

I use this official sample from Microsoft:

When I try to access the MyLabel from codebehind in the click event the MyLabel is NULL.

Why this?

<asp:ScriptManager ID="PageScriptManager" runat="server" />
<asp:Button ID="MyButton" Text="Click Me" runat="server" onClick="MyButton_Clicked" />
<asp:UpdatePanel ID="MyUpdatePanel" runat="server">
<Triggers> 
    <asp:AsyncPostBackTrigger ControlID="MyButton" EventName="Click" />
</Triggers>
    <ContentTemplate>
    <asp:Label ID="MyLabel" Text="OldText" runat="server" />
    </ContentTemplate>
</asp:UpdatePanel>




private void MyButton_Clicked(object sender, EventArgs e) 
 {   
  MyLabel.Text = "NewText!";
 } 

UPDATE This code does not work Why? The MyLabel is always NULL on server side ??

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

  <asp:ScriptManager runat="server" ID="xx">  
  </asp:ScriptManager>

 <asp:ImageButton OnClick="OnClickRefreshButton" ID="RefreshImageButton" runat="server" Width="100px" />
<asp:UpdatePanel ID="MyUpdatePanel" runat="server"> 
    <Triggers>
         <asp:AsyncPostBackTrigger ControlID="RefreshImageButton" EventName="Click" /> 
    </Triggers> 
    <asp:ContentTemplate> 
      <asp:Label ID="MyLabel" Text="OldText" runat="server" />
    </asp:ContentTemplate>
</asp:UpdatePanel>  
</asp:Content>

protected void OnClickRefreshButton(Object sender, ImageClickEventArgs e) 
        {       

            MyLabel.Text = "NewText!";
        }

Upvotes: 0

Views: 2635

Answers (2)

TheNewOne
TheNewOne

Reputation: 1711

Try to change the function to protected and not private, it worked for me. hope it solved your problem

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can adjust UpdateMode="Conditional" to your Updatepanel

LInk : http://msdn.microsoft.com/fr-fr/library/system.web.ui.updatepanel.updatemode.aspx

Upvotes: 0

Related Questions