Dave
Dave

Reputation: 205

Checkchanged not firing when inside a gridview in asp.net

I have a gridview and inside it is a checkbox for the status of the items, the checkbox has checkchanged event but when I'm trying to check or uncheck it, the checkchanged is not firing.

here is the code for the gridview with checkbox inside

 <asp:GridView ID="dgvItems" runat="server" OnRowCreated="dgvItems_RowCreated" OnRowDataBound="dgvItems_RowDataBound" OnSelectedIndexChanged="dgvItems_SelectedIndexChanged" OnRowDeleting="dgvItems_RowDeleting">
   <Columns>
       <asp:TemplateField HeaderText ="Status">
           <ItemTemplate>
              <asp:CheckBox ID="chkStatus" runat="server" Checked = <%# (string)Eval("item_status") == "Active" ? true : false %> OnCheckedChanged="chkStatus_CheckedChanged" AutoPostBack="True" />
           </ItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>

 protected void chkStatus_CheckedChanged(object sender, EventArgs e)
    {
        GridViewRow row = dgvItems.SelectedRow;
        string item_id = row.Cells[0].Text.ToString();

        con.Open();
        SqlCommand cmd = new SqlCommand("Update Items set item_status = 'Inactive' where item_id = @item_id ",con);
        cmd.Parameters.AddWithValue("@item_id", cmd);
        cmd.ExecuteNonQuery();

        con.Close();
    }

Thanks in Advance!

Upvotes: 0

Views: 350

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460298

Two things are coming to my mind:

  1. Your Page_Load does not take care of the IsPostBack-property, so you are always databinding the grid, even on postback. That prevents events.
  2. GridViewRow row = dgvItems.SelectedRow; is null.

Use this code to get the GridViewRow from the checked CheckBox:

CheckBox chkStatus = (CheckBox) sender;
GridViewRow row = (GridViewRow) chkStatus.NamingContainer;

Upvotes: 1

Nalaka
Nalaka

Reputation: 1185

If your checked state is initially false, then setting it to false again doesn't fire the CheckedChanged event. That happens because the checked state isn't actually changed

This is the internal code used when trying to set the CheckBox1.Checked property

public void set_Checked(bool value)
{
if (value != this.Checked)
{
    this.CheckState = value ? CheckState.Checked : CheckState.Unchecked;
}
}

Upvotes: 0

Related Questions