gpt4 book ai didi

C# 在 site master 中添加控件不会在 asp :loginView 中引用

转载 作者:行者123 更新时间:2023-11-30 20:55:29 25 4
gpt4 key购买 nike

我有一个网站管理员,我正在添加一些控件,其中一个是通过编程方式更新的标签。我不确定为什么在第二个示例中我不能引用该对象,如果我对范围在站点管理员中的工作方式的理解是错误的。如有任何帮助,我们将不胜感激!

这个“ClubName”标签按预期工作

 <div class="main">
<asp:Label ID="ClubName" runat="server"></asp:Label>
</div>

虽然这个没有(对象引用未设置为对象的实例)

<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<AnonymousTemplate>
[ <a href="~/Account/Login.aspx" ID="HeadLoginStatus" runat="server">Log In</a> ]
</AnonymousTemplate>
<LoggedInTemplate>
Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /></span>!
[ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
<asp:Label ID="ClubName" runat="server" Text="Label"></asp:Label>
</LoggedInTemplate>
</asp:LoginView>

我的代码背后的代码很简单

public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
NameClub.Text = "hello";
}

和异常错误:

 Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

最佳答案

Label ClubName= HeadLoginView.FindControl("ClubName") as Label;
if(ClubName != null)
ClubName.Text = "hello";

您的 aspx 标签 ID 是 ClubName,但在您的代码中,您将其访问为 NameClub。无论如何,您不能直接访问 LoginView 内的控件。使用 FindControl 方法并获取上述控件。

你最好阅读 How to: Access Server Controls by ID

关于C# 在 site master 中添加控件不会在 asp :loginView 中引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18265591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com