简体   繁体   中英

How to hide a div using an ASP.NET Checkbox?

i'm trying to do this assigning an method to the event on the checkbox tag like this:

    OnCheckedChanged="ShowDiv"

However, i'm not succesfull at all. How to do it? Here's my method:

    public void ShowDiv(object sender, System.EventArgs e) 
    {
        var div = FindControl("ListaEmOutrosDocumentos") as HtmlGenericControl;
        var checkbox = FindControl("Principal") as CheckBox;

        if(checkbox.Checked == true)
        {
            div.Style.Clear();
            div.Style.Add("display","block");
        }
        else
        {
            div.Style.Clear();
            div.Style.Add("display","none");
        }
    }

You might consider using an ASP.NET Panel control instead of a div . That will have a Visible property that you can set.

I did this and it worked.

<div id="ListaEmOutrosDocumentos" runat="server">
            <asp:CheckBox runat="server" ID="Principal" AutoPostBack="True" OnCheckedChanged="ShowDiv"/>
        </div>

Code Behind

public void ShowDiv(object sender, System.EventArgs e)
    {
        var div = ListaEmOutrosDocumentos as HtmlGenericControl;
        var checkbox = sender as CheckBox;

        if (checkbox.Checked == true)
        {
            div.Style.Clear();
            div.Style.Add("display", "block");
        }
        else
        {
            div.Style.Clear();
            div.Style.Add("display", "none");
        }
    }

Quick way using server side code only

Aspx

<div id="myDiv" runat="server" style="height:200px;width:100px;background-color:Blue"></div>
<asp:CheckBox ID="chkShowHideDiv" runat="server" AutoPostBack="True" 
    oncheckedchanged="chkShowHideDiv_CheckedChanged" Text="Hide Div"  />

Code behind

 protected void chkShowHideDiv_CheckedChanged(object sender, EventArgs e)
{
    myDiv.Visible = chkShowHideDiv.Checked ? false : true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM