user2259263
user2259263

Reputation: 29

Label won't show when label hidden via page load

The desired effect is that on page load the label does not display but when the user clicks the check box the label displays. This small code sample is just a sample to illustrate the issue. The code will always return an object reference exception from javascript when the Visible property of the label is set to false. If that line is commented out, it will execute correctly with no object reference exceptions but the label should be hidden at page load. This application does use master pages which is why were are passing the ClientIDs to the javascript Toggle function.

protected void Page_Load(object sender, EventArgs e)
{
    this.chkSelect.Attributes.Add("onClick", "Toggle('" + this.lblAdd.ClientID + "', '" + this.chkSelect.ClientID + "')");
    this.lblAdd.Visible = false;
}

<script type="text/javascript">
    function Toggle(lblAdd, chk) {
        var ctrlAdd = document.getElementById(lblAdd);
        var ctrlChk = document.getElementById(chk);

        if (ctrlChk.checked == true) {
            ctrlAdd.style.display = 'inline';
        }
        else {
            ctrlAdd.style.display = 'none';
        }
    }
</script>


    <asp:Label ID="lblAdd" runat="server" Text="Add" Font-Size="8pt" ForeColor="Blue"> </asp:Label>
    <asp:CheckBox ID="chkSelect" runat="server" Text="Check Box1" /><br />

How can we hide that label in Page_Load so we don't get object reference errors from Internet Explorer?

Thanks...

Upvotes: 1

Views: 877

Answers (1)

TimCodes.NET
TimCodes.NET

Reputation: 4699

the Visible property does not render the HTML if set to false, that's why you get a null reference (in other words, ASP.NET's Visible is nothing to do with the display CSS property - it actually toggles whether an element is rendered in the HTML code or not.). Instead assign a CSS class on page load that defines display: none, then remove that class on click with javascript

Upvotes: 5

Related Questions