Click here to Skip to main content
14,574,806 members

Using CheckBoxes within the DataGrid control to select records

Rate this:
4.32 (29 votes)
Please Sign up or sign in to vote.
4.32 (29 votes)
3 Jul 2004CPOL
This article is about using CheckBoxes in a Datagrid control to select records as in a mail box.


The problem can be stated as follows:

  1. There should be a checkbox in the header to check all and uncheck all.
  2. There should be checkboxes with individual records to select the records individually.
  3. The check all check box on the header should be checked if all the records are individually selected.
  4. There should be an external button outside the DataGrid by which we should be able to retrieve checked records.

Sample screenshot


The records that are retrieved in the DataGrid is from a table which I have created. The script for creating the table in SQL Server is as follows:

CREATE TABLE [dbo].[Anz_Contacts] (
       [Id] [int] IDENTITY (1, 1) NOT NULL ,
       [FirstName] [char] (10)  NULL ,
       [LastName] [char] (10)  NULL ,
       [Designation] [varchar] (50)  NULL       
       )  ON [PRIMARY] 

Sample screenshot

On the Page_Load event, the DataGrid is bound to the table. The code for binding DataGrid is shown below:

Note: Change the connection string which suits your DBMS, cnnDB and myDataGrid are protected member variables.

private void Page_Load(object sender, System.EventArgs e)
    cnnDB = new SqlConnection("server=HOME;user id=sa;password=;database=Contacts");
    if (!IsPostBack)
private void bindGrid()
    SqlDataAdapter da = new SqlDataAdapter("select * from Anz_Contacts",cnnDB);
    DataSet ds = new DataSet();
    da.Fill(ds, "Employees");

Now that we have seen how we bind the data to the grid, we will look at how the HTML of the DataGrid looks like:

<form id="Form1" name="Form1" method="post" runat="server">
<ASP:DATAGRID id="myDataGrid" 











       <HeaderStyle BackColor="NavajoWhite"></HeaderStyle>
       <FooterStyle BackColor="NavajoWhite"></FooterStyle>
              <asp:TemplateColumn HeaderText="contract">
       <input type="checkbox" id="checkAll"

 onclick="CheckAll(this);" runat="server" name="checkAll">
                           <input type="checkbox" runat="server" id="EmpId"

 onclick="CheckChanged();" checked='false' name="EmpId" />
              <asp:TemplateColumn HeaderText="Id">
                           <asp:Label id="Id" Text='<%# 
DataBinder.Eval(Container.DataItem, "Id") %>' runat="server" />
              <asp:BoundColumn DataField="FirstName"

              <asp:BoundColumn DataField="LastName" 

              <asp:BoundColumn DataField="Designation" 

</form >

Notice the TemplateColumn in the DataGrid. TemplateColumn represents a column type for the DataGrid control that allows you to customize the layout of controls in the column. I have used the template column to render check boxes in the header and the item templates. I have used the HtmlInputCheckBox control rather than a <asp:CheckBox> control. This is because the checking and unchecking is strictly a client side process and there is no need for server side manipulation here. The checkbox in the header will call the client script function CheckAll() when it is clicked, and the checkbox in the record items will call CheckChanged() function.

I have used the second TemplateColumn to include a Label control to display the ID column from the table. This Label control will help us later to get the ID of the selected records. The rest of the columns are bound with FirstName, LastName and Designation using the BoundColumn of DataGrid.

Now we will take a look at the client side JavaScript functions to manipulate the checking and unchecking.

If we are using VS.NET and a code behind model, it is preferable to use the RegisterClientScriptBlock method of the page to emit client-side script blocks in the page. The client script registering is done when the page is loaded. So we can write the code for it on the Page_load event of the page.

The JavaScript function CheckAll() is as follows. I have constructed the script string using string concatenation, for readability. You can use the StringBuilder class for more efficient concatenation.

string strScript;
strScript= " <script language=JavaScript>                             ";
strScript+=" function CheckAll( checkAllBox )                         ";
strScript+=" {                                                                  ";
strScript+=" var frm = document.Form1;                               ";
strScript+="  var ChkState=checkAllBox.checked;                   ";
strScript+="  for(i=0;i< frm.length;i++)                                 ";
strScript+="  {                                                                 ";
strScript+="         e=frm.elements[i];                                   ";
strScript+="        if(e.type=='checkbox' &&'Id') != -1)";
strScript+="            e.checked= ChkState ;                        ";
strScript+="  }                                                               ";
strScript+=" }                                                                ";
strScript+="  </script>                                                     ";
       this.RegisterClientScriptBlock("clientScriptCheckAll", strScript);

In the above script, we first checked the state of the CheckBox that fired the event, i.e., the header CheckBox. Next, we loop through the form elements searching for all CheckBox controls which have the word "Id" in their name to set the value of the CheckBoxes to match that of the Header CheckBox.

The JavaScript function which is called when the checkboxes in each record item is checked or unchecked is as follows. Here we are checking whether all the records are selected or not to determine the checked state of the checkAll checkbox in the header.

strScript= "<script language=JavaScript>                              ";
strScript+="function CheckChanged()                                   ";
strScript+="{                                                                   ";
strScript+="  var frm = document.Form1;                              ";
strScript+="  var boolAllChecked;                                         ";
strScript+="  boolAllChecked=true;                                       ";
strScript+="  for(i=0;i< frm.length;i++)                                 ";
strScript+="  {                                                                 ";
strScript+="    e=frm.elements[i];                                        ";
strScript+="  if ( e.type=='checkbox' &&'Id') != -1 )";
strScript+="      if(e.checked== false)                                  ";
strScript+="      {                                                             ";
strScript+="         boolAllChecked=false;                               ";
strScript+="         break;                                                    ";
strScript+="      }                                                              ";
strScript+="  }                                                                  ";
strScript+="  for(i=0;i< frm.length;i++)                                  ";
strScript+="  {                                                                  ";
strScript+="    e=frm.elements[i];                                         ";
strScript+="    if ( e.type=='checkbox' &&'checkAll') != -1 )";
strScript+="    {                                                            ";
strScript+="      if( boolAllChecked==false)                         ";
strScript+="         e.checked= false ;                                ";
strScript+="         else                                                    ";
strScript+="         e.checked= true;                                  ";
strScript+="      break;                                                    ";
strScript+="    }                                                             ";
strScript+="   }                                                              ";
strScript+=" }                                                                ";
strScript+=" </script>                                                     ";
       this.RegisterClientScriptBlock("clientScriptCheckChanged", strScript);

Now, what is left is to use an external button outside the DataGrid for retrieving checked records. Add this code inside the form which contains the DataGrid:

<asp:button id="selBtn" onclick="View_Selected" runat="server" 

name="selBtn" text="Show Selection"></asp:button>

The event handler of the button:

public void View_Selected(object sender, EventArgs e)
    foreach( DataGridItem di in myDataGrid.Items )
        HtmlInputCheckBox chkBx = (HtmlInputCheckBox)di.FindControl("EmpId") ;
        if( chkBx !=null && chkBx.Checked )
            Label lbl = (Label)di.FindControl("Id");
            Response.Write( lbl.Text +"<br>" );

We loop through each DataGridItem contained within the DataGrid and search for the HtmlInputCheckBox control and then check its value. If it is checked, we search for the Label control in the DataGridItem to get the “ID” field. Once we get the ID, we write it to the Response.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
India India
Just another Developer

Comments and Discussions

GeneralMy vote of 5 Pin
rakesh700828-Mar-13 20:53
Memberrakesh700828-Mar-13 20:53 
GeneralWonderful article -- put it right to use! Pin
rendeb2-Sep-09 11:12
Memberrendeb2-Sep-09 11:12 
GeneralI am giveing u 4 mks Pin
santosh d30-Apr-09 8:43
Membersantosh d30-Apr-09 8:43 
GeneralHi Good article Pin
Ganesan Sankaran26-Nov-07 20:07
MemberGanesan Sankaran26-Nov-07 20:07 
Generalgood Pin
Member 380403119-Feb-07 19:34
MemberMember 380403119-Feb-07 19:34 
GeneralChecking the Checkbox State Pin
naveenieus2-Jan-07 18:46
Membernaveenieus2-Jan-07 18:46 
QuestionCheck Box within a Data Grid Pin
jdbss7-Nov-06 8:37
Memberjdbss7-Nov-06 8:37 
Generalcheckall Pin
paolo silva3-Nov-06 16:29
Memberpaolo silva3-Nov-06 16:29 
GeneralCheck boxes with tables in ASP Pin
LearnFrmGurus18-Sep-06 23:15
MemberLearnFrmGurus18-Sep-06 23:15 
GeneralCheckBox is still considered as a SERVER control !!! Pin
abhiace21-Jul-06 6:17
Memberabhiace21-Jul-06 6:17 
GeneralReading CheckBoxes in a DataGrid Pin
OmegaCD11-Jun-06 15:51
MemberOmegaCD11-Jun-06 15:51 
GeneralThanks! Pin
delta118631-May-06 14:53
Memberdelta118631-May-06 14:53 
Questionhow to select a row in datagrid by checking the check box in that row Pin
Siva Myneni26-May-06 23:40
MemberSiva Myneni26-May-06 23:40 
GeneralAccessing datagrid items from outer page Pin
satyajit_g6-Mar-06 23:56
Membersatyajit_g6-Mar-06 23:56 
JokeMark Fraser Pin
therota9-Feb-06 9:31
Membertherota9-Feb-06 9:31 
GeneralError on Some Servers! Pin
Adel Khayata20-Jan-06 9:49
MemberAdel Khayata20-Jan-06 9:49 
Generalsmall optimization Pin
ernest_elias14-Dec-05 22:14
Memberernest_elias14-Dec-05 22:14 
GeneralRe: small optimization Pin
TulsaDev12-Jun-06 6:15
MemberTulsaDev12-Jun-06 6:15 
QuestionCheckAll(...) question Pin
iammudman4-Nov-05 8:44
Memberiammudman4-Nov-05 8:44 
AnswerRe: CheckAll(...) question Pin
Ansil6-Nov-05 19:42
MemberAnsil6-Nov-05 19:42 
GeneralRe: CheckAll(...) question Pin
iammudman6-Nov-05 19:56
Memberiammudman6-Nov-05 19:56 
QuestionCan someone guide me in the right direction. Pin
Ian Perera18-Oct-05 15:52
MemberIan Perera18-Oct-05 15:52 
AnswerRe: Can someone guide me in the right direction. Pin
NelsonRodriguez20059-Nov-05 9:19
MemberNelsonRodriguez20059-Nov-05 9:19 
GeneralRe: Can someone guide me in the right direction. Pin
alerizwe19-Feb-07 21:13
Memberalerizwe19-Feb-07 21:13 
GeneralFilter and show data in data grid Pin
meanu29-Sep-05 9:30
Membermeanu29-Sep-05 9:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 3 Jul 2004


88 bookmarked