Using Checkbox in ASP.NET GridView Control

Waqas Anwar
08 February 2009
152242 Views

This tutorial will show you how to use CheckBox inside GridView and how to handle its events to update database records based on its Checked state.

ASP.NET GridView Control provides developers ability to use any type of ASP.NET control in its columns using TemplateField. Developers are free to use Buttons, DropDownList, RadioButtons or any other control according to their application requirement. One of the most common control developers uses in the GridView is CheckBox control and if you are creating Administration Panel of any ASP.NET Application you may be required to handle checkbox event to update any back end database table. One Typical example is to Enable/Disable status of any record in the database table using the CheckBox in the GridView. In the following tutorial I will show you how you can use CheckBox in the GridView which not only display the current status of the record but also update the record status in the database.



CheckBox in GridView



To start this tutorial, I am assuming that you have table in your database with one Bit type column such as Approved in the following figure.


gridview_checkbox_db.gif

Categories Table in SQL Server 2005


I will update the status of this column to True or False according to the state of the checkbox in the GridView. The Page Load event binds your Database Categories Table to your GridView Control.
 

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    LoadData();
  }
}

private void LoadData()
{
  string constr = @"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
  string query = @"SELECT CategoryID, CategoryName, Approved FROM Categories";

  SqlDataAdapter da = new SqlDataAdapter(query, constr);
  DataTable table = new DataTable();
  da.Fill(table);

  GridView1.DataSource = table;
  GridView1.DataBind();
}

Please keep in mind that I put connection string directly in the code just for the demonstration. You should store your database connection string in web.config file. You can also call stored procedure in the above code if you don’t want to write SQL Query directly in your code or you can also call your Data Access Layer component to retrieve Categories Table from database. The following ASP.NET source will show you how you can use TemplateField in the GridView to display CheckBox with the current status of the Category in the database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"  
    CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
    Font-Names="Arial" GridLines="Vertical" Width="40%">
           
            <Columns>            
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkStatus" runat="server"
                            AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
                            Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
                            Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
                    </ItemTemplate>                   
                </asp:TemplateField>
               
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />                   
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName"  />
            </Columns>
           
    <HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
          
</asp:GridView>

In the above code see how I am setting Checked State of the CheckBox from the Approved Column value in the database. I am also setting the Text Property of the CheckBox Approved or Not Approved according to the state of Approved Column in database. To provide user option to update the status of any Category from the CheckBox I am also setting AutoPostBack Property to true and adding Event Handler chkStatus_OnCheckedChanged to handle OnCheckedChanged event. Every time user will check or uncheck the CheckBox this event will update the status of Approved Column in the Database.
 

public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
    CheckBox chkStatus = (CheckBox)sender;
    GridViewRow row = (GridViewRow)chkStatus.NamingContainer;

   
    string cid = row.Cells[1].Text;
    bool status = chkStatus.Checked;

   
    string constr = @"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
    string query = "UPDATE Categories SET Approved = @Approved WHERE CategoryID = @CategoryID";
       
    SqlConnection con = new SqlConnection(constr);
    SqlCommand com = new SqlCommand(query, con);

   
    com.Parameters.Add("@Approved", SqlDbType.Bit).Value = status;
    com.Parameters.Add("@CategoryID", SqlDbType.Int).Value = cid;

   
    con.Open();
    com.ExecuteNonQuery();
    con.Close();
   
    LoadData();
}


In the above code, first four lines are doing the main job. I am getting the reference of CheckBox by type casting the sender parameter of the Event Handler. To get the CategoryID I am getting reference of the entire GridViewRow object. The remaining code is straight forward ADO.NET code to execute the Update Query in Database using SqlConnection and SqlCommand object.