简体   繁体   中英

ASP.NET C# CheckBox does not fire CheckedChanged event when unchecking

I have repeater

<asp:Repeater ID="rptResult" runat="server" >
        <ItemTemplate>
            <tr>
                <td>
                  <asp:CheckBox ID="chkShipStatus" runat="server"  EnableViewState="true" ViewStateMode = "Enabled" AutoPostBack="True"  CommandName='<%# DataBinder.Eval(Container.DataItem, "CT")%>'    OnCheckedChanged="chkShipStatus_CheckedChanged"  Checked='<%# Convert.ToBoolean(Eval("SHIPPED")) ? true : false %>'  />

                </td>
            </tr>
        </ItemTemplate>
</asp:Repeater>

and

and call data from page_load

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            DataTable dt = ap.GetDataTable(sql);
            rptResult.DataSource = dt;
            rptResult.DataBind();
         }
       //go there and finish when unchecd

    }

and here is my CheckedChanged event it call only when i cheched not firing when i unchecked it go to page_load(not incycle !postback)

     protected void chkShipStatus_CheckedChanged(object sender, EventArgs e)
    {
        var cb = (CheckBox)sender;
       //go there when i checked
         if (cb.Checked == true)
        {
            //go there when i checked

        }
        else
        {
           //never go in here when i uncheck
        }
    }

A CheckBox has no CommandName property so remove it

<asp:CheckBox ID="chkShipStatus" runat="server"  EnableViewState="true" ViewStateMode = "Enabled" 
             AutoPostBack="True"        
             OnCheckedChanged="chkShipStatus_CheckedChanged"  
             Checked='<%# Convert.ToBoolean(Eval("SHIPPED")) ? true : false %>'  
/>

if you want to know in which item the checkbox was you can use NamingContainer . Then use repeaterItem.FindControl to get another control in that RepeaterItem . So you could for example use a HiddenField to store the ID of the record.

protected void chkShipStatus_CheckedChanged(object sender, EventArgs e)
{
    var cb = (CheckBox)sender;
    RepeaterItem item = (RepeaterItem) cb.NamingContainer
    HiddenField hiddenID = (HiddenField) item.FindControl("HiddenID");
    string id = hiddenID.Value;
    // ...
}

you say :

it call only when i cheched not firing when i unchecked it go to page_load(not incycle !postback)

so what is the code in the load ?? it may has some code that prevents the uncheck process

If you have SHIPPED column values like 1 OR 0 then I recommend you to update below attribute of your checkbox control. I tried it and chkShipStatus_CheckedChanged event calling for me.

Checked='<%# Convert.ToString(Eval("SHIPPED")) == "1" ? true : false %>'

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