简体   繁体   中英

Unable to uncheck checkbox with postback

I've got several checkboxes which are used to hide and unhide asp.net panels, I've done this using C# which is why I needed the postback.

Now initially the panels are hidden and my code works fine when checked, but when I try to uncheck them they retain their values after postback and the panels are still visible.

Here's my code:

Markup:

<asp:CheckBox ID="cbxHideShow" runat="server" AutoPostBack="true" OnCheckedChanged="cbxHideShow_CheckedChanged" Text="Hide/Show Panel"/>

and code-behind:

protected void cbxHideShow_CheckedChanged(object sender, EventArgs e)
{
    if (cbxHideShow.Checked = true)
    {
        Panel1.Visible = true;
    }
    else
    {
        Panel1.Visible = false;
    }
}

If someone could let me know what I'm doing wrong I would very much appreciate it.

You are using the assignment operator ( = ) where you should be using the equality operator ( == ).

if (cbxHideShow.Checked == true)

Better yet, omit the operator completely since cbxHideShow.Checked is a boolean already:

if (cbxHideShow.Checked)

Of course, you don't even need the if statement at all. You could just do this:

protected void cbxHideShow_CheckedChanged(object sender, EventArgs e)
{
    Panel1.Visible = cbxHideShow.Checked;
}

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