Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update database on checkbox change in gridview asp.net c#

Tags:

c#

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.

like image 577
Minhaj Avatar asked Feb 18 '23 06:02

Minhaj


2 Answers

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();
    }
}
like image 125
Tim Schmelter Avatar answered Feb 21 '23 01:02

Tim Schmelter


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.
}
like image 26
sreejithsdev Avatar answered Feb 21 '23 03:02

sreejithsdev