Search
Categories
  ASP.NET
Visual C#
Visual Basic
.NET Framework
ADO.NET
AJAX
LINQ
Java
 
Tutorial Rating
 
3.4 out of 5


Total Votes: 42
         
1 2 3 4 5
 


Using Checkbox in ASP.NET GridView Control

Author: Waqas Anwar - Posted Date: 08-February-2009 - Category: ASP.NET   
Send this page to friend Bookmark and Share
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.

gridview_checkbox.JPG

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.JPG

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.

 



RELATED TUTORIALS

  Using Button columns in GridView
  Displaying Total in Footer of GridView
  Editing Data using ASP.NET GridView Control
  Using Hyperlink columns in GridView
  Deleting multiple Rows in GridView using Checkbox
  Formatting GridView output based on Data
  Deleting multiple Rows in GridView using Checkbox
  Display images in DataList from Database

LEAVE YOUR COMMENTS LEAVE YOUR COMMENTS
 Name (required)  
 Email (required
 Website


 
POSTED COMMENTS POSTED COMMENTS

Great! I was trying to have a checkbox be either enable or disabled based on a boolean value in my sql query and this allowed me to do that. Thanks!
Posted by Jan Ole Peek on Thursday, July 23, 2009

Asalam-o-Alaikum

sir can elaborate this sgment while Eval checkbox text value

Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved "
Posted by zeeshan on Friday, September 25, 2009

I tried this, but still every single click on checkbox control, isn't firing anything even with autpostback in true; also I dont have any validators or required controls in this form, what could be happenning? VS 2005
Posted by Rawler on Thursday, December 17, 2009

 
Your Name


Your Email


Friend Name


Friend Email


 
Sending Email...


 
 
 

Categories

My Portfolio

Website Links


Copyright @ 2009 EzzyLearning.com