我使用微软的官方样本:
当我尝试在click事件中从代码隐藏访问MyLabel时,MyLabel为NULL。
为什么会这样?
<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!";
}
更新此代码不起作用为什么?服务器端的MyLabel始终为NULL ??
<%@ 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!";
}
答案 0 :(得分:1)
尝试将功能更改为protected
而不是private
,这对我有用。希望它能解决你的问题
答案 1 :(得分:0)
您可以将UpdateMode="Conditional"
调整为Updatepanel
LInk:http://msdn.microsoft.com/fr-fr/library/system.web.ui.updatepanel.updatemode.aspx