4

I have a CheckBox in GridView cell. I want to update the database on CheckBox change, like when I unchecked it, 'Status' column in table update as false or vice versa.

0

2 Answers 2

7

Your question is very incomplete. But i'll give it a try, maybe it's helpful anyway.

Assuming you want to update as soon as the Checked state has changed(the user clicked the CheckBox), you have to set AutoPostBack="true" first.

Then you can handle the CheckBox.CheckedChanged event:

protected void Check_Clicked(Object sender, EventArgs e)
{
    // get the checkbox reference
    CheckBox chk = (CheckBox)sender;
    // get the GridViewRow reference
    GridViewRow row = (GridViewRow) chk.NamingContainer;
    // assuming the primary key value is stored in a hiddenfield with ID="HiddenID"
    HiddenField hiddenID = (HiddenField) row.FindControl("HiddenID");

    string sql = "UPDATE dbo.Table SET Status=@Status WHERE idColumn=@ID";
    using (var con = new SqlConnection(connectionString))
    using (var updateCommand = new SqlCommand(sql, con))
    {
        updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
        // assuming the type of the column is bit(boolean)
        updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
        con.Open();
        int updated = updateCommand.ExecuteNonQuery();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Grid source

<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:CheckBox ID="chkview" runat="server" AutoPostBack="true" OnCheckedChanged="chkview_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>

C# code

protected void chkview_CheckedChanged(object sender, EventArgs e)
{
     // code here.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.