2

我正在尝试更改在 .net 4.0 中创建新网站时提供给您的默认 login.aspx 页面中创建的标签的文本。我似乎无法以任何方式访问此标签。如果用户未获得批准,则单击登录按钮时文本应该会更改。这里是制作标签的地方。

    <LayoutTemplate>
        <span class="failureNotification">
            <asp:Literal ID="FailureText" runat="server"></asp:Literal>
        </span>
        <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification" 
             ValidationGroup="LoginUserValidationGroup"/>
             <%-- If the account is not approved display an error message --%>
        <asp:Label ID="NotAproved" runat="server" CssClass="failureNotification"></asp:Label>......

我试图通过使用 FindControl 来访问它,但它从来没有工作过,所以我可能做错了什么。预先感谢您的帮助。

编辑:我在后面的代码中找到了访问它的方法,以防万一有人有类似的问题:

    var notApproved = (Label)LoginUser.FindControl("NotApproved");
    notApproved.Text = "Sorry Your Account has not yet Been Approved by an Administrator. Try Again Later.";
4

1 回答 1

1

The FindControl method will only find server side controls (as in this case) that are direct descendants of the container you are searching. From MSDN (I have added emphasis)-

Use FindControl to access a control from a function in a code-behind page, to access a control that is inside another container, or in other circumstances where the target control is not directly accessible to the caller. This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls. For information about how to find a control when you do not know its immediate container, see How to: Access Server Controls by ID.

http://msdn.microsoft.com/en-us/library/486wc64h.aspx

Generally you should avoid using FindControl and reference the control directly using the ID in order to return the strongly typed object and avoid a tight dependency on a particular control hierarchy, but this isn't possible for controls added within templates as you have probably found.

It seems you have either stumbled upon or worked out the direct descendent requirement by yourself, but I would suggest the following may be safer code-

var notApproved = LoginUser.FindControl("NotApproved") as Label;
if (notApproved != null)
{
    notApproved.Text = "Sorry Your Account has not yet Been Approved by an Administrator. Try Again Later.";
}

This deals with the NullReferenceException you would get if LoginUser.FindControl("NotApproved") doesn't find anything and returns Null (see the above MSDN link) and also a possible type cast exception where the object found is not a label and cannot be cast to one.

于 2013-07-13T14:54:44.197 回答