Click here to Skip to main content
11,577,429 members (39,131 online)
Click here to Skip to main content

Using CheckBoxes within the DataGrid control to select records

, 3 Jul 2004 CPOL 244.5K 3.3K 88
Rate this:
Please Sign up or sign in to vote.
This article is about using CheckBoxes in a Datagrid control to select records as in a mail box.

Introduction

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

Solution

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]
GO
ALTER TABLE [dbo].[Anz_Contacts] WITH NOCHECK ADD 
       CONSTRAINT [PK_Anz_Contacts] PRIMARY KEY  CLUSTERED 
       (
              [Id]
       )  ON [PRIMARY] 
GO

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)
        bindGrid();
}
private void bindGrid()
{
    SqlDataAdapter da = new SqlDataAdapter("select * from Anz_Contacts",cnnDB);
    DataSet ds = new DataSet();
    da.Fill(ds, "Employees");
    myDataGrid.DataSource=ds.Tables["Employees"].DefaultView;
    myDataGrid.DataBind();
}

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" 
runat="server" 
AutoGenerateColumns="false" 
HeaderStyle-BackColor="#aaaadd" 
Font-Size="8pt" 
Font-Name="Verdana" 
CellSpacing="0" 
CellPadding="3" 
ShowFooter="true" 
BorderColor="Black"
BackColor="AntiqueWhite" 
Width="600">
       <HeaderStyle BackColor="NavajoWhite"></HeaderStyle>
       <FooterStyle BackColor="NavajoWhite"></FooterStyle>
       <Columns>
              <asp:TemplateColumn HeaderText="contract">
                     <HeaderTemplate>
       <input type="checkbox" id="checkAll"
 onclick="CheckAll(this);" runat="server" name="checkAll">
                     </HeaderTemplate>
                     <ItemTemplate>
                           <input type="checkbox" runat="server" id="EmpId"
 onclick="CheckChanged();" checked='false' name="EmpId" />
                     </ItemTemplate>
                           </asp:TemplateColumn>
              <asp:TemplateColumn HeaderText="Id">
                     <ItemTemplate>
                           <asp:Label id="Id" Text='<%# 
DataBinder.Eval(Container.DataItem, "Id") %>' runat="server" />
                     </ItemTemplate>
              </asp:TemplateColumn>
              <asp:BoundColumn DataField="FirstName"
       HeaderText="FirstName"></asp:BoundColumn>
              <asp:BoundColumn DataField="LastName" 
HeaderText="LastName"></asp:BoundColumn>
              <asp:BoundColumn DataField="Designation" 
HeaderText="Designation"></asp:BoundColumn>
       </Columns>
</ASP:DATAGRID>
</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' && e.name.indexOf('Id') != -1)";
strScript+="            e.checked= ChkState ;                        ";
strScript+="  }                                                               ";
strScript+=" }                                                                ";
strScript+="  </script>                                                     ";
if(!this.IsClientScriptBlockRegistered("clientScriptCheckAll"))
       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="";
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' && e.name.indexOf('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' && e.name.indexOf('checkAll') != -1 )";
strScript+="    {                                                            ";
strScript+="      if( boolAllChecked==false)                         ";
strScript+="         e.checked= false ;                                ";
strScript+="         else                                                    ";
strScript+="         e.checked= true;                                  ";
strScript+="      break;                                                    ";
strScript+="    }                                                             ";
strScript+="   }                                                              ";
strScript+=" }                                                                ";
strScript+=" </script>                                                     ";
if(!this.IsClientScriptBlockRegistered("clientScriptCheckChanged"))
       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.

License

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

Share

About the Author

Ansil
Software Developer (Senior)
India India
Ansil hails from Trivandrum.
He works for Microsoft india (R&D ).
he blogs at http://ansilf.spaces.live.com/



"First they ignore you;then they laugh at you ;then they fight you ;then you win "

You may also be interested in...

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
coolnaveen12342-Jan-07 18:46
membercoolnaveen12342-Jan-07 18:46 
QuestionCheck Box within a Data Grid Pin
Jim Bilsky7-Nov-06 8:37
memberJim Bilsky7-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
sivamyneni26-May-06 23:40
membersivamyneni26-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    Rant Rant    Admin Admin   

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 4 Jul 2004
Article Copyright 2004 by Ansil
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid