SharePoint - SharePoint GridView Groupby count
Asked By Anandha Babu
27-Sep-11 11:04 AM
Hi All,
I am using SharePoint Grid view in my custom aspx page where i have an option group the SharePoint Grid view by various factor such as title, id , user etc. Here i need to display the Group by count for each items. such as
Group A (12)
Group B (13) etc.
Any idea to achieve it.
Radhika roy replied to Anandha Babu

Grouping with SPGridView
the following code renders an SPGridView that shows the item-level permissions grouped by user. Also, even though the item-level permissions are sometimes assigned to SPGroups, I iterate through each group and display each item-level permission per user.
DisplayPermissionsByUser.cs
using System;
using System.Data;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using SPFormUtilities;
namespace ListItemPermissionsReport
{
public class ReportListingByUser : LayoutsPageBase
{
protected SPGridView grdListItemPermissions;
protected Label lblError, lblListName;
protected override void OnLoad(EventArgs e)
{
grdListItemPermissions.AllowGrouping = true;
grdListItemPermissions.GroupField = "User";
grdListItemPermissions.GroupFieldDisplayName = "";
grdListItemPermissions.GroupImageDescriptionField = "";
grdListItemPermissions.AllowGroupCollapse = true;
try
{
SPWeb web = this.Web;
// Get a reference to the roles that are bound to the user and the site's role
// definition for full control to which we need to verify the user against
SPRoleDefinitionBindingCollection usersRoles = web.AllRolesForCurrentUser;
SPRoleDefinitionCollection siteRoleCollection = web.RoleDefinitions;
SPRoleDefinition roleDefinition = siteRoleCollection["Full Control"];
// Check whether the user is an admin
if ((usersRoles.Contains(roleDefinition)) || web.CurrentUser.IsSiteAdmin)
{
if (IsPostBack != true)
{
if (CheckValidUrl())
{
lblError.Visible = false;
initPage();
}
else
{
lblError.Text = @"The list ID parameter ('list') is missing from the address.";
grdListItemPermissions.Visible = false;
}
}
}
else
Response.Redirect("/_layouts/accessdenied.aspx");
}
catch (Exception ex)
{
Utilities.sendError(ex, "ListItemPermissionsReport.OnLoad");
}
}
private bool CheckValidUrl()
{
// Check whether the list ID was included as a request parameter
string listId = "";
//get the list id (guid in a string format) from the query string
listId = Request.QueryString["list"];
//make sure the list parameter was passed
if (listId == null)
return false;
else
return true;
}
private string UrlEncode(string text)
{
return Server.UrlEncode(text).Replace("+", "%20");
}
private void initPage()
{
// Create a DataTable to hold the list item permission report data.
DataTable dt = new DataTable();
dt.Columns.Add("User");
dt.Columns.Add("ItemLink");
dt.Columns.Add("Permissions");
// Use an SPGridView to display the data.
// Create a BoundField for each column that will be displayed in the SPGridView.
BoundField userField = new BoundField();
userField.DataField = "User";
userField.HeaderText = "User";
userField.ItemStyle.Wrap = false;
userField.SortExpression = "User";
userField.HtmlEncode = true;
BoundField itemLinkField = new BoundField();
itemLinkField.DataField = "ItemLink";
itemLinkField.HeaderText = "Item Link";
itemLinkField.ItemStyle.Wrap = false;
itemLinkField.SortExpression = "ItemLink";
itemLinkField.HtmlEncode = false;
BoundField permissionsField = new BoundField();
permissionsField.DataField = "Permissions";
permissionsField.HeaderText = "Permissions";
permissionsField.SortExpression = "Permissions";
permissionsField.HtmlEncode = true;
// Add the columns to the SPGridView.
grdListItemPermissions.Columns.Add(userField);
grdListItemPermissions.Columns.Add(itemLinkField);
grdListItemPermissions.Columns.Add(permissionsField);
// Populate the DataTable with the group name, user name, item link,
// and permissions for each item in the list.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(this.Site.ID))
{
using (SPWeb web = site.OpenWeb(this.Web.ID))
{
SPList list = web.Lists[new Guid(Request.QueryString["list"])];
// Populate the list name
lblListName.Text = list.Title;
// Create a query that returns all the items in a list
SPQuery query = new SPQuery();
bool isDocLib = false;
if (list is SPDocumentLibrary)
isDocLib = true;
foreach (SPListItem item in list.Items)
{
string[] rowValue;
StringBuilder roleList;
string principalItemPermissions;
// Get the item's title
string itemTitle;
if (isDocLib)
itemTitle = item.Name;
else
itemTitle = item.Title;
string encodedItemTitle = Server.HtmlEncode(itemTitle);
// Parse the string of the URL. Delimit by slash.
// URL encode each chunk.
// Put back together.
// Get the item's URL.
string itemURL = web.Url + "/" + item.Url;
// Get rid of "http://"
string itemURLblob = itemURL.Substring(7);
string[] itemURLchunks = itemURLblob.Split('/');
string encodedItemURL = "http://";
foreach (string chunk in itemURLchunks)
encodedItemURL += (UrlEncode(chunk) + "/");
// Get rid of last '/'
encodedItemURL = encodedItemURL.Remove(encodedItemURL.LastIndexOf('/'));
// Add InfoPath form functionality if file is xml
if (encodedItemURL.EndsWith(".xml"))
encodedItemURL += "?OpenIn=Browser";
// Construct the link
string itemLink = "<a href=" + encodedItemURL + " target=_blank>" + encodedItemTitle + "</a>";
// Get the item-level permissions
SPRoleAssignmentCollection roles = item.RoleAssignments;
foreach (SPRoleAssignment roleAssignment in roles)
{
roleList = new StringBuilder();
foreach (SPRoleDefinition roleDef in roleAssignment.RoleDefinitionBindings)
roleList.Append(roleDef.Name + ", ");
// Delete the trailing ", "
roleList.Remove(roleList.Length - 2, 2);
principalItemPermissions = roleList.ToString();
if (roleAssignment.Member is SPGroup)
{
SPGroup group = (SPGroup)roleAssignment.Member;
foreach (SPUser user in group.Users)
{
// Add the group, item link, and permissions to the DataTable
rowValue = new string[3];
rowValue[0] = user.Name;
rowValue[1] = itemLink;
rowValue[2] = principalItemPermissions;
dt.Rows.Add(rowValue);
}
}
else // SPUser
{
// Add the user, item link, and permissions to the DataTable
rowValue = new string[3];
rowValue[0] = roleAssignment.Member.Name;
rowValue[1] = itemLink;
rowValue[2] = principalItemPermissions;
dt.Rows.Add(rowValue);
}
}
}
dt.AcceptChanges();
DataView dv = dt.DefaultView;
dv.Sort = "User ASC";
// Bind the DataView to the SPGridView
grdListItemPermissions.DataSource = dv;
grdListItemPermissions.DataBind();
}
}
});
}
}
}
DisplayPermissionsByUser.aspx
The javascript code collapses the groups on page load.
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Title="List Item Permissions Report"
Inherits="ListItemPermissionsReport.ReportListingByUser, ListItemPermissionsReport, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e6e76cfeade18a79"
EnableViewState="false" EnableViewStateMac="false" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
List Item Permissions Report By User
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
runat="server">
List Item Permissions Report By User
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<asp:Label runat="server" ID="lblListName" Font-Bold="true" /><br />
<asp:Label runat="server" ID="lblError" />
<SharePoint:SPGridView runat="server" ID="grdListItemPermissions" AutoGenerateColumns="false"
RowStyle-BackColor="#DDDDDD" AlternatingRowStyle-BackColor="#EEEEEE" />
<script type="text/javascript">
var rows = document.getElementsByTagName('tr');
var numRows = rows.length;
for (var i = 0; i < numRows; ++i) {
if (rows[i].getAttribute("isexp") != null && rows[i].getAttribute("isexp").toLowerCase() == "true") {
if (rows[i].firstChild.firstChild != null && rows[i].firstChild.firstChild.tagName.toLowerCase() == "a") {
if (rows[i].firstChild.firstChild.title.toLowerCase() == "expand/collapse") {
rows[i].firstChild.firstChild.fireEvent("onclick");
}
}
}
}
</script>
</asp:Content>
Radhika roy replied to Anandha Babu
this link would help you
http://www.sharepointblogs.com/bobsbonanza/archive/2007/07/02/filtering-with-spgridview.aspx
This is the definitive guide on SPGridView.
visit these links also
Devil Scorpio replied to Anandha Babu
Hi,
Try this in footer for SP gridview groupby count
myGridView.DataSource = myDataSet;
myGridView.DataMember = myDataSet.Tables[0];
string NrOfRecords = myDataSet.Tables[0].Rows.Count;
NICK NICK replied to Anandha Babu

WorkFlow Association Query SharePoint I am associating the OOTB Approval Workflow to the Pages Library in the child sub SPWorkflowAssociation GetWorkFlowAssociation(SPFeatureReceiverProperties properties) { SPWeb currentWeb; SPList _pagesLibrary; SPList _workflowTaskList; SPList _workflowHistoryList = null; SPWorkflowAssociation _approvalWorkFlowAssociation; StringBuilder _sbApprovalWorkflowAssociation; currentWeb = properties.Feature.Parent as SPWeb; _approvalWorkFlowAssociation = SPWorkflowAssociation.CreateListAssociation(currentWeb.WorkflowTemplates.GetTemplateByName(Resources.Strings _workflowHistoryList); _approvalWorkFlowAssociation.AllowAsyncManualStart = true; _approvalWorkFlowAssociation.AllowManual = true; _approvalWorkFlowAssociation.AutoStartChange = true; _approvalWorkFlowAssociation.AutoStartCreate = true; _sbApprovalWorkflowAssociation = new StringBuilder(); _sbApprovalWorkflowAssociation.Append("<my:myFields xml:lang = \ "en-us \ " xmlns:xsi = \ http: / / www.w3.org / 2001 / XMLSchema-instance \ xmlns:my = \ "http: / / schemas.microsoft.com / office / infopath / 2003 / myXSD \ "> "); _sbApprovalWorkflowAssociation.Append("<my:Reviewers> "); _sbApprovalWorkflowAssociation.Append("<my:Person> "); _sbApprovalWorkflowAssociation.Append("<my:DisplayName> KPMG you let me know what I may have to change / set to achieve this? Thanks SharePoint Development Discussions SPWorkflowAssociation.CreateListAssociation (1) SPFeatureReceiverProperties (1) Resources.Strings.ApprovalWorkFlowAssociationName (1) Resources.Strings.ApprovalWorkFlowAssocationData (1
SharePoint / InfoPath SharePoint I have an InfoPath Form that i need to keep track of the usage of. I want to have it submit to a Sharepoint list so i can export the data to a Pivot Table when needing audited. Is an idea on what to do to achieve this? Thanks for your help in advance SharePoint Discussions SharePoint (1) InfoPath (1) SpottedOrange (1) Ivan (1) Screenshots (1) Iasanders (1) Matt provides a simple example with
Sharepoint + Infopath SharePoint Hi All, We have MOSS 2007. I have setup an Anonymous Access site and want to be able to open a blank Infopath Job application form, ask the user to fill it out, then when the user clicks and have them complete the form, submit it, then have the completed forms stored in Sharepoint. When one is completed to shoot out an email to HR for their review. Any suggestion is welcome. Thanks, AD SharePoint Design Discussions SharePoint (1) MOSS 2007 (1) AirDuster101 (1 Infopath (1) Applicants (1) Toollbars (1) Litle (1) On Sep 4, 8:26 pm, AirDuster101 Very
the right permissions on the content type. Then, I created a column "external data" in Sharepoint that I linked to my content type. When I want to change the data in EventID Level Message Correlation 11 / 13 / 2011 00:08:30.31 w3wp.exe (0x1D9C) 0x1038 SharePoint Foundation Monitoring nasq Medium Entering monitored scope (Request (GET:http: / / tricoflex:80 / CRM / _layouts / FldNewEx Cust%2E%20Relation%20ID&DescriptionParam = &VldFormulaParam = &VldMessageParam = )) 11 / 13 / 2011 00:08:30.31 w3wp.exe (0x1D9C) 0x1038 SharePoint Foundation Logging Correlation Data xmnv Medium Name = Request (GET:http: / / tricoflex:80 / CRM / _layouts / FldNewEx e307-4c5d-b470-c4351e5dff53 11 / 13 / 2011 00:08:30.32 w3wp.exe (0x1D9C) 0x1038 SharePoint Foundation Logging Correlation Data xmnv Medium Site = / 9694064f-e307-4c5d-b470-c4351e5dff53 11 / 13 / 2011 00:08:30.35 w3wp.exe (0x1D9C) 0x1038 SharePoint Foundation Monitoring b4ly Medium Leaving Monitored Scope (Request (GET:http: / / tricoflex:80 / CRM / _layouts / FldNewEx e307-4c5d-b470-c4351e5dff53 11 / 13 / 2011 00:08:30.45 wsstracing.exe (0x06A0) 0x17A0 SharePoint Foundation Unified Logging Service b9wt High Log retention limit reached. Log file 'C: \ Program Files log' has been deleted. 11 / 13 / 2011 00:08:30.45 wsstracing.exe (0x06A0) 0x17A0 SharePoint Foundation Tracing Controller Service 8096 Information Usage log retention limit reached. Some old usage log files have been deleted. 11 / 13 / 2011 00:08:30.57 w3wp.exe (0x1D9C) 0x1038 SharePoint Foundation Monitoring nasq Medium Entering monitored scope (Request (GET:http: / / tricoflex:80 / SiteAssets / SitePages / Accueil