Skip to content Skip to sidebar Skip to footer

Control Does Not Exist. Why?

I have my setup below. When rendering the page it throws this error: The name 'UserName' does not exist in the current context. I don't understand why because my control is right a

Solution 1:

The Login control, among others like Repeaters and GridViews, use templates. This takes the controls in those template tags, like the Login's <LayoutTemplate>, out of the Page.Controls list, and puts them in the Login tag's Controls list. So you need a reference to the control within the Login control's list.

This code uses the FindControl() method which iterates through all the direct children of the control looking for an ID by name. The full code below explicitly casts it to the target type, but you could cast to the more generic Control if it would be easier since you're only getting the ClientID property:

((Control)Login1.FindControl("UserName")).ClientID

Also, the Login control is a little special in that it expects certain controls with specific IDs, so it won't render the literal, client-side JavaScript code in the Login LayoutTemplate. So move the literal <script> tag outside of the template. This doesn't solve the reference problem of course, so you still must get a reference to the child control with FindControl().

<asp:Login ID="Login1" runat="server">
    <LayoutTemplate>
        <asp:TextBox ID="Password" runat="server" Width="136px"></asp:TextBox>
        <asp:TextBox ID="UserName" runat="server" Width="136px"></asp:TextBox>
        <asp:CustomValidator ID="cvUserNameOrEmailRequired" ValidationGroup="LoginForm" runat="server"
            CssClass="input-error" ErrorMessage="Username is required" ControlToValidate="UserName"
            Display="Dynamic" ClientValidationFunction="UsernameValidateTextBox" ValidateEmptyText="True">
        </asp:CustomValidator>
    </LayoutTemplate>
</asp:Login>
<script type="text/javascript">
    function UsernameValidateTextBox(source, arguments) {
        if (arguments.Value % 2 == 0) {
            arguments.IsValid = false;
        } else {
            arguments.IsValid = true;
        }
    }
    $("#<%= ((TextBox)Login1.FindControl("UserName")).ClientID %>").focus(function () {
        $("#<%=((CustomValidator)Login1.FindControl("cvUserNameOrEmailRequired")).ClientID %>").css({ visibility: "hidden" });
    });
</script>

Post a Comment for "Control Does Not Exist. Why?"