Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

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

4.82/5 (9 votes)
7 Apr 2009CPOL6 min read 77K   1.2K  
An article about Creating CheckAll UncheckAll Gridview webpart with Paging, Sorting functionalities in Sharepoint 2007 in step by step manner

Introduction

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:

OutputScreen.JPG

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.NET
<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">
<Columns>
<asp:TemplateField HeaderText="All" ItemStyle-HorizontalAlign="Left">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick="SelectOrUnselectAll(this,'chkRow')" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" onclick="Check('chkRow')" />
</ItemTemplate>
</asp:TemplateField>
<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"
SortExpression="EmployeeDesignation"
ItemStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="EmployeeEmail" HeaderText="Employee Email" 
	SortExpression="EmployeeEmail"
ItemStyle-HorizontalAlign="Left" />
<asp:TemplateField SortExpression="EmployeeEmail"
Visible="false">
<HeaderTemplate>
Employee Email
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblEmail" Text='<%# Bind("EmployeeEmail") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

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

C#
protected void GetData()
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        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 = 
				listItem["EmployeeDesignation"].ToString();
                        }
                        if (listItem["EmployeeEmail"] != null)
                        {
                            employeeEmail = listItem["EmployeeEmail"].ToString();
                        }
                        AddDataToTable(employeeId, employeeName, 
				employeeDesignation, employeeEmail, 
				(DataTable)Session[GridValues]);
                    }
                }
            }
        }
    });
}

(b) Sample Code for Sorting

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

C#
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;
gvMail.DataBind();

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

C#
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;

gvMail.DataBind();

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

C#
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.

C#
WebUserControl = (UserControl)Page.LoadControl
(@"/_controltemplates/GridViewUserControl.ascx");

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

else
{
    this.Controls.Add(WebUserControl);
}
  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:

      CreateStrongKey.JPG

  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

    XML
    <SafeControl Assembly="[Web
    part Assembly Name], Version=1.0.0.0, Culture=neutral, 
    	PublicKeyToken=[PublicKeyTokenValue]"
    Namespace="[Web Part Namespace Name]"
    
    TypeName="*" Safe="True"
    AllowRemoteDesigner="True"/>

Note

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.

    LutzReflector.JPG

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

    IISAPP.JPG

  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.

    AttachProcess.JPG

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

History

  • 7th April, 2009: Initial post

License

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