C# – oncheckedchanged not firing for CheckBox when in GridView

asp.netcgridviewoncheckedchanged

I'm trying to have a OnCheckedChanged event fire for an asp:CheckBox which is within a GridView. But when I put it into a GridView it does not fire the OnCheckedChanged in the code-behind.

If I put the same checkbox outside of the gridview, it's perfectly fine.

I've tried setting the function as a RowCommand and that doesn't work either.

Here is my checkbox:

<asp:CheckBox ID="HoldBillingCheckBox" runat="server" key='<%# Eval("CustomerItemID") %>' Checked='<%# Eval("HoldBilling") %>' OnCheckedChanged="CustomerItemsGridView_CheckChanged" Enabled="true" EnableViewState="true" AutoPostBack="true"/>

It seems to me that this only occurs when you are trying to wrap the CheckBox with any view.

Does anyone have any suggestions? I've googled so many different solutions but nothing seems to work (they are mainly telling me to add AutoPostBack as true…or enableviewstate as true).

thanks in advance!

Best Answer

If you are rebinding your gridview on each load of the page, then you are destroying the statefulness of the CheckChanged event. When you rebind your grid, it invalidates any controls that were in the previous "version" of the page.

You need to add if (!IsPostBack) as a conditional to prevent your GridView from rebinding.