Click here to Skip to main content
13,557,707 members
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 7 Apr 2009
Licenced CPOL

Creating CheckAll UncheckAll Gridview Webpart with Paging, Sorting Functionalities in Sharepoint 2007 in a Step by Step Manner

, 7 Apr 2009
Rate this:
Please Sign up or sign in to vote.
An article about Creating CheckAll UncheckAll Gridview webpart with Paging, Sorting functionalities in Sharepoint 2007 in step by step manner


This article helps:

  1. To know how to provide sorting, paging, Check All and Uncheck All functionality for a gridview in SharePoint
  2. To read a SharePoint custom list and bind it to ASP.NET Gridview control
  3. To know how to call a User control in a SharePoint web part
  4. To understand how to deploy the web part
  5. To know how to debug the web part

This is what we are going to achieve at the end of this article:


User Control in SharePoint

In webparts in general all the controls are created at run time. But when this task becomes too tedious then write user controls in ASP.NET and use them in SharePoint webparts.

How to Use the Code

Unzip the provided sample code GridView control. The solution contains two projects. The first project is for creating an ASP.NET Gridview usercontrol along with a test webpage. The second project is for creating a SharePoint Webpart using the above Gridview usercontrol.

Creating a Custom List in SharePoint

In the sample code, a custom list by name “EmployeeList“ was created in SharePoint site (http://[systemnumber]:[portnumber]) for populating the gridview.

Steps to Create SharePoint Custom List

  1. In the SharePoint site, i.e. (http://[systemnumber]:[portnumber]) click Site Actions >> Create.
  2. From the Create page, click the Custom List link under the Custom Lists category.
  3. From the New page, enter a title “EmployeeList” and then click the Create button.
  4. Then from the newly created list’s page, click the Create Column link under the Settings menu.
  5. From the Create Column page, enter the name of the column and type, e.g. SingleLine of Text.
  6. Repeat steps 4 and 5 for all the columns [Title, EmployeeName, EmployeeDesignation, EmployeeEmail].

Once all the columns have been created, click on New Item link under the list’s New menu to add an item to the list. And enter some records for “EmployeeList”.

Create User Control

  1. Open Visual Studio IDE, Select File >> New>> Project, select “Visual C#” as language and under “Web” select “Web Application” template.
  2. Now the Solution file can be shown in the “Solution Explorer”
  3. Click on References and select “Add References” option.
  4. Select “Windows SharePoint Services” from the .NET tab, with this Microsoft.Sharepoint.dll is added in the References.
  5. Right click on project >> Add >> New Item >> select WebUserControl.
  6. Following functionalities are provided in the Gridview user control:
    1. Getting data from SharePoint List
    2. Creating the Gridview header rows at run time
    3. Pagination
    4. Sorting
    5. CheckAll & UncheckAll checkboxes- for getting the Ids of the selected rows, in the following sample Email Ids are taken.

      Place a Gridview control from the toolbox in ascx page.
      Write JavaScript for getting the checkall and UncheckAll functionality in the gridview control.

Sample User Control ascx Code

Check the GridViewUsercontrol.ascx code for JavaScript.

<asp:GridView ID="gvMail" runat="server" AutoGenerateColumns="False" 

	Width="752px" AllowPaging="True" AllowSorting="True" PageSize="5" 

	OnPageIndexChanging="gvMail_PageIndexChanging" OnSorting="gvMail_Sorting" 

	HorizontalAlign="Left" UseAccessibleHeader="false">
<asp:TemplateField HeaderText="All" ItemStyle-HorizontalAlign="Left">
<asp:CheckBox ID="chkAll" runat="server" onclick="SelectOrUnselectAll(this,'chkRow')" />
<asp:CheckBox ID="chkRow" runat="server" onclick="Check('chkRow')" />
<asp:BoundField DataField="Title" HeaderText="User Id"

SortExpression="Title" ItemStyle-HorizontalAlign="Left"

<asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" 

	SortExpression="EmployeeName" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="EmployeeDesignation" HeaderText="Employee Designation"


ItemStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="EmployeeEmail" HeaderText="Employee Email" 


ItemStyle-HorizontalAlign="Left" />
<asp:TemplateField SortExpression="EmployeeEmail"

Employee Email
<asp:Label ID="lblEmail" Text='<%# Bind("EmployeeEmail") %>' runat="server" />

(a) Sample Code for Getting Data from SharePoint List

In the below code “EmployeeList” is the SharePoint Custom list name and http://[systemnumber]:[portnumber] is the site where webpart gets deployed.

Hold the data in a session.

protected void GetData()
        using (SPSite site = new SPSite("http://systemno:portnumber"))
            using (SPWeb web = site.OpenWeb())
                SPList list = web.Lists["EmployeeList"];
                SPListItemCollection itemColl;
                SPQuery query = new SPQuery();

                itemColl = list.GetItems(query);

                string employeeId = string.Empty;
                string employeeName = string.Empty;
                string employeeDesignation = string.Empty;
                string employeeEmail = string.Empty;

                if (itemColl.Count > 0)
                    for (int icount = 0; icount < itemColl.Count; icount++)
                        SPListItem listItem = itemColl[icount];
                        if (listItem["Title"] != null)
                            employeeId = listItem["Title"].ToString();
                        if (listItem["EmployeeName"] != null)
                            employeeName = listItem["EmployeeName"].ToString();
                        if (listItem["EmployeeDesignation"] != null)
                            employeeDesignation = 
                        if (listItem["EmployeeEmail"] != null)
                            employeeEmail = listItem["EmployeeEmail"].ToString();
                        AddDataToTable(employeeId, employeeName, 
				employeeDesignation, employeeEmail, 

(b) Sample Code for Sorting

Hold the sort expression, i.e. column names and sort direction ascending or descending in viewstate variables.

DataTable dtSort = ((DataTable)Session[GridValues]);
string lastExpression = string.Empty;
if (ViewState["SortExpression"] != null)
lastExpression = ViewState["SortExpression"].ToString();

string lastDirection = "asc";
if (ViewState["SortDirection"] != null)
lastDirection = ViewState["SortDirection"].ToString();

string newDirection = "asc";
if (e.SortExpression == lastExpression)
newDirection = (lastDirection == "asc") ? "desc" : "asc";

ViewState["SortExpression"] = e.SortExpression;
ViewState["SortDirection"] = newDirection;

DataView dvSort = new DataView(dtSort);
dvSort.Sort = e.SortExpression + " " + newDirection;
gvMail.DataSource = dvSort;

(c) Sample Code for Pagination

Take care of sorting during pagination. So read the SortExpression i.e. column name and sort direction from the viewstate.

this.gvMail.PageIndex = e.NewPageIndex;
DataTable dtPagination = ((DataTable)Session[GridValues]);
DataView dvPagination = new DataView(dtPagination);

if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)

dvPagination.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];

gvMail.DataSource = dvPagination;


(d) Sample Code for Selecting the Emails

Loop through all the checkboxes and using FindControl method, find the selected checkboxes and as per the requirement like sending mails to those or deleting records implement it.

foreach (GridViewRow i in gvMail.Rows)
    CheckBox chkRowItem = (CheckBox)i.FindControl("chkRow");
    if (chkRowItem.Checked)
        emailIds += ((Label)i.FindControl("lblEmail")).Text.ToString() + ",";

Testing the User Control

For testing the user control functionality before adding it to a web part, add a web form to the project and call the user control in the web page so that the user control can be tested. Find the attached source code to check the functionality of user control in web page.

In the ascx page for Gridview this property “UseAccessibleHeader=false” is required for proper alignment of header checkbox with other checkboxes.

Adding the User Control in a Web Part

  1. Add new project to the same solution, select Visual C# as language and Windows >>Class Library
  2. Add “System.Web” as reference in the References of the project.
  3. Add a class file.
  4. Call user control in the class file for making it as webpart.

Sample Code for Calling User Control in the Class Library

GridViewUserControl.ascx is the name of the user control that was created in earlier steps.

WebUserControl = (UserControl)Page.LoadControl

if (WebUserControl == null)
    this.Page.Response.Write("usercontrol null");

  1. Build the solution.

Deploying the Web Part

  1. Copy the user control file (*.ascx) in the path- “SharePoint Installation Drive\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\CONTROLTEMPLATE/usercontrolfilename.ascx
  2. Copy the DLL of the user control in the path-"SharePoint Installation Drive\Inetpub\wwwroot\wss\VirtualDirectories\[Site Port No.]\bin\
  3. Create Strong name key.
    1. Right click on the web part project, go to “properties”
    2. Select “signing” tab from left side
    3. Check the “Sign the assembly” checkbox
    4. Select “New” from the below drop down. ”Create Strong Name Key” Window opens.
    5. Uncheck the “Protect my Keyfile with a password”, enter name in the “Key File Name” textbox, then click “ok”.

      Check the below screen for reference:


  4. Drag and drop the web part DLL in GAC (Type “assembly” in Start -> Run to open the Assembly folder directly).
  5. Add Safe Control tag in the web.config file of this path- SharePoint Installation Drive\Inetpub\wwwroot\wss\VirtualDirectories\[Site Port No.]\web.config

    <SafeControl Assembly="[Web
    part Assembly Name], Version=, Culture=neutral, 
    Namespace="[Web Part Namespace Name]"
    TypeName="*" Safe="True"


Get the Public Key Token value in two ways:

  1. From the Assembly folder, right click on the DLL (or deployed assembly) and go to properties and copy the Public Key Token value.
  2. Use Lutz Reflector. Helps in getting more information about .NET assemblies. Download from here.


  1. Do iisreset.

Adding the Web part in the Web Part Gallery

  1. Navigate to the site URL – http://[Site Port No.]
  2. Go to Site Actions>> Site Settings>>Galleries>>Webparts>>Web Part Gallery
  3. Click on “New” button of “Web parts Gallery” page. ”Web Part Gallery: New Web Parts” page gets opened, Select the deployed web part from the list below and click on “Populate Gallery” button
  4. If web part already exists, check the “Overwrite if file already exists” checkbox and click on “Populate Gallery” button

Using the Web Part in the Site Home Page

  1. Navigate to the Site Home Page
  2. Go to Site Actions>>Edit Page
  3. Click on “Add a Web Part” and the opened window contains the list of all web parts
  4. Under Miscellaneous section, select the previously deployed web part and then click on “Add” button.
  5. Click Exit Edit mode

Now the Gridview webpart is displayed with Paging, sorting and CheckAll and UnCheckAll options are displayed.

Debugging the Web Part

  1. Start>> Run>> Type cmd
  2. Type “cd\” in the command prompt window, then type IISAPP.vbs and press enter type IISAPP.vbs is used to get the Process ID of SharePoint site.

    (Refer the below screen shot, in this case the process ID is 2784.)


  3. In Visual Studio go to Debug>> Attach to Process >> and check for the Process “w3wp.exe” and Process ID 2784.
  4. Select the process and click on “Attach” button.


  5. Add breakpoints in the application and debug the web part like any other .NET project.


  • 7th April, 2009: Initial post


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


About the Author

Web Developer
India India
I am Sreedhar Ambati working as a developer. I am having 6+ yrs of experience in Microsoft technologies like ASP,VB,ASP.Net, Vb.Net, C#.Net, Microsoft Dynamics CRM and Sharepoint Server 2007.
I used to blog at: and

You may also be interested in...


Comments and Discussions

GeneralAdvanced grid view webpart Pin
Isha Attlee9-Nov-10 17:39
memberIsha Attlee9-Nov-10 17:39 
GeneralJeitson Guerrero B. Pin
jeitson6-May-10 12:58
memberjeitson6-May-10 12:58 
GeneralNullReferenceException Pin
soufiene6-Apr-10 7:29
membersoufiene6-Apr-10 7:29 
GeneralAttribute 'onclick' is not a valid attribute of element 'CheckBox'. Pin
jl_peque14-Jan-10 4:50
memberjl_peque14-Jan-10 4:50 
GeneralRe: Attribute 'onclick' is not a valid attribute of element 'CheckBox'. Pin
jl_peque14-Jan-10 6:18
memberjl_peque14-Jan-10 6:18 
GeneralGrid is not displaying Pin
rajender.g13-Dec-09 21:53
memberrajender.g13-Dec-09 21:53 
QuestionRegarding Session variables Pin
jeymal29-Jun-09 20:55
memberjeymal29-Jun-09 20:55 
GeneralGrid not displayed in sharepoint site [modified] Pin
vikpri28-Apr-09 10:30
membervikpri28-Apr-09 10:30 
GeneralRe: Grid not displayed in sharepoint site Pin
ambatisreedhar28-Apr-09 23:27
memberambatisreedhar28-Apr-09 23:27 
GeneralRe: Grid not displayed in sharepoint site Pin
pri8329-Apr-09 2:46
memberpri8329-Apr-09 2:46 
GeneralRe: Grid not displayed in sharepoint site Pin
vikpri29-Apr-09 10:51
membervikpri29-Apr-09 10:51 
GeneralFix for pagination Pin
ambatisreedhar13-Apr-09 20:15
memberambatisreedhar13-Apr-09 20:15 
GeneralThank you Pin
rajanawasreh12-Apr-09 16:08
memberrajanawasreh12-Apr-09 16:08 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180515.1 | Last Updated 7 Apr 2009
Article Copyright 2009 by ambatisreedhar
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid