DebPepDevuan
DebPepDevuan

Reputation: 489

Run an event when Checkbox is Checked/Unchecked Gridview C#

I have a Gridview that has 4 columns. All in ItemTemplate One column is a CheckBox. This Gridview is binded to a datasource. What I want to do is when the Checkbox is checked update the database with the bit value '1' and if I uncheck the Checkbox to do the same but '0'.

I already know my SQL code to update the database, but I am not sure how to run the event so that it looks at the current row the checkbox is on in the gridview.

Here is the CheckBox Column.

<asp:TemplateField  HeaderText="Pick" ItemStyle-CssClass="hrGrid" HeaderStyle-CssClass="hdrHrBase">
<ItemTemplate>
<asp:CheckBox id="cbViewCustomer" runat="server" OnCheckedChanged="ViewCustomer" onAutoPostBack="true" Checked='<%#(Eval("chosen"))%>'/>        
</ItemTemplate>
</asp:TemplateField>

Do I use EventArgs like this: The problem with this is it updates the database but all the rows. What I am trying to do is update only the current row that is in the Gridview. I am just not sure where to go from here.

protected void ViewCustomer(object sender, EventArgs e)
    {
        string SelectCustomer = "UPDATE tblcustomer Set chosen ='0'";
        NpgsqlCommand changedata = new NpgsqlCommand(SelectCustomer, con);
        con.Open();
        changedata.ExecuteNonQuery();
        con.Close();

    }

Or should I be doing something different?

Upvotes: 0

Views: 4653

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

You can do this with OnRowCommand event of gridview like this:-

Associate a RowCommand event with your gridview:-

<asp:GridView ID="mygridview" runat="server" OnRowCommand="mygridview_OnRowCommand">

Next, associate a CommandName & CommandArgument to your checkbox:-

<asp:TemplateField  HeaderText="Pick" ItemStyle-CssClass="hrGrid" >
   <ItemTemplate>
     <asp:CheckBox id="cbViewCustomer" runat="server" Checked='<%#(Eval("chosen"))%>' 
         CommandName="myCheckbox" CommandArgument="<%# Container.DataItemIndex %>"/>
   </ItemTemplate>
</asp:TemplateField>

In the code behind handle the event:-

protected mygridview_OnRowCommand (object sender, GridViewCommandEventArgs e)
{
     if(e.CommandName == "myCheckbox")
     {
          int rowIndex = Convert.ToInt32(e.CommandArgument);
          GridViewRow row = mygridview.Rows[rowIndex];
          bool ischecked = (row.FindControl("cbViewCustomer") as CheckBox).Checked;
     }
}

You can also do it with checbox checked event, but if you have multiple controls then fire the gridview command event instead of individual events.

Upvotes: 1

Related Questions