Link to home
Start Free TrialLog in
Avatar of kvigor
kvigor

asked on

GridView Sorting in SharePoint WebPart: Sorting not working

I have a GridView that gets populated from a CAML Query, and I'm merely trying to enable Sorting on the Gridview but for some reason the "gridview.AllowSorting = true;" isn't making a difference.
FYI: All code works except Sorting...
View Full Code Below:
using System;
using System.Security.Principal;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebControls;
using System.Security.Permissions;
using System.Drawing;
using System.Globalization;
using System.DirectoryServices;
 
 
namespace ExecutiveTaskRollup
{
    public class TaskRollup : System.Web.UI.WebControls.WebParts.WebPart
    {
        GridView tasksCollection;
        string userName;
        string fullName;
        string searchFilter;
 
        #region User Stuff
        protected string GetCurrentLoggedInUser()
        {
            searchFilter = "(samaccountname=";
 
            userName = HttpContext.Current.User.Identity.Name.ToString();
            userName = userName.Substring(4) + ")";
 
            searchFilter = searchFilter + userName;
            fullName = GetActiveADUsers("LDAP://adbox.company.com", searchFilter);
 
            return fullName;
        }
 
        public string GetActiveADUsers(string ldapString, string adSearchFilter)
        {
            DirectoryEntry de = new DirectoryEntry(ldapString, "domain\\user", "password");
            DirectorySearcher deSearch = new DirectorySearcher(de, adSearchFilter);
 
            deSearch.SearchScope = SearchScope.Subtree; //Including the sub OU's
 
            SearchResult result = deSearch.FindOne();
 
            string fullName = result.Properties["name"][0].ToString().Trim();
 
            return fullName;
        }
 
        #endregion
        protected override void CreateChildControls()
        {
            //base.CreateChildControls();
            tasksCollection = new GridView();
            tasksCollection.AllowSorting = true;
            tasksCollection.AutoGenerateColumns = false;
            tasksCollection.HeaderStyle.BorderStyle = BorderStyle.None;
            tasksCollection.BorderStyle = BorderStyle.None;
            tasksCollection.GridLines = GridLines.None;
            tasksCollection.CellPadding = 5;
            tasksCollection.CellSpacing = 0;
            tasksCollection.AlternatingRowStyle.BackColor = System.Drawing.Color.FromKnownColor(KnownColor.Lavender);
            tasksCollection.Sorting += new GridViewSortEventHandler(tasksCollection_Sorting);
 
            //Bind Columns Needed
            BoundField titleField = new BoundField();
            titleField.HtmlEncode = false;
            titleField.HeaderText = "Title";
            titleField.DataField = "Title";
            tasksCollection.Columns.Add(titleField);
 
            BoundField priorityField = new BoundField();
            priorityField.HtmlEncode = false;
            priorityField.HeaderText = "Priority";
            priorityField.DataField = "Priority";
            tasksCollection.Columns.Add(priorityField);
 
            BoundField assignedToField = new BoundField();
            assignedToField.HtmlEncode = false;
            assignedToField.HeaderText = "Assigned To";
            assignedToField.DataField = "AssignedTo";
            tasksCollection.Columns.Add(assignedToField);
 
            BoundField statusField = new BoundField();
            statusField.HtmlEncode = false;
            statusField.HeaderText = "Status";
            statusField.DataField = "Status";
            tasksCollection.Columns.Add(statusField);
 
            BoundField percentCompleteField = new BoundField();
            percentCompleteField.HtmlEncode = false;
            percentCompleteField.HeaderText = "Percent Complete";
            percentCompleteField.DataField = "PercentComplete";
            tasksCollection.Columns.Add(percentCompleteField);
 
            BoundField modifiedField = new BoundField();
            modifiedField.HtmlEncode = false;
            modifiedField.HeaderText = "Modified";
            modifiedField.DataField = "Modified";
            modifiedField.ApplyFormatInEditMode = true;
            tasksCollection.Columns.Add(modifiedField);
 
            BoundField authorField = new BoundField();
            authorField.HtmlEncode = false;
            authorField.HeaderText = "Author" + fullName;
            authorField.DataField = "Author";
            tasksCollection.Columns.Add(authorField);
 
            Controls.Add(tasksCollection);
        }
 
        protected void tasksCollection_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dtAllowTableSorting = tasksCollection.DataSource as DataTable;
 
            if (dtAllowTableSorting != null)
            {
                DataView dvSortedView = new DataView(dtAllowTableSorting);
                dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
 
                tasksCollection.DataSource = dvSortedView;
                tasksCollection.DataBind();
            }
        }
 
        private string getSortDirectionString(System.Web.UI.WebControls.SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;
            if (sortDirection == System.Web.UI.WebControls.SortDirection.Ascending)
            {
                newSortDirection = "ASC";
            }
            else
            {
                newSortDirection = "DESC";
            }
 
            return newSortDirection;
        }
 
        protected override void OnPreRender(EventArgs e)
        {
            fullName = GetCurrentLoggedInUser();
            int athrInd, asgnToInd;
 
 
            SPSite siteCol = SPContext.Current.Site;
            SPWeb site = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedSiteCol = new SPSite(siteCol.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedSiteCol.OpenWeb(site.ID))
                    {
                        try
                        {
                            // Declaring Query Object
                            SPSiteDataQuery qry = new SPSiteDataQuery();
 
                            // Defining Query Object
                            qry.Query = "<Where><Or><Eq><FieldRef Name='AssignedTo' /><Value Type='Text'>" + fullName + "</Value></Eq><Eq><FieldRef Name='Author' /><Value Type='Text'>" + fullName + "</Value></Eq></Or></Where>";//Use this Query for Production
 
                            // Defining Columns to View
                            qry.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Priority' /><FieldRef Name='Status' /><FieldRef Name='PercentComplete' /><FieldRef Name='AssignedTo' /><FieldRef Name='Modified' /><FieldRef Name='Author' />";
 
                            // Setting List Type
                            qry.Lists = "<Lists ServerTemplate='107' />";
                            qry.Webs = "@<Webs Scope= 'SiteCollection' />";
 
                            //***First SPCONTEXT CHANGE! (Didn'WORK)
                            //DataTable table = SPContext.Current.Site.RootWeb.GetSiteData(qry);
                            DataTable table = ElevatedSiteCol.RootWeb.GetSiteData(qry);
 
                            #region Formating Percentage
                            foreach (DataRow row in table.Rows)
                            {
                                //Add hyyperlink to Title
                                Guid listID = new Guid(row["ListId"].ToString());
                                Guid webID = new Guid(row["WebId"].ToString());
 
                                string url = SPContext.Current.Site.Url;
                                //float dbl;
 
                                //***Second SPCONTEXT CHANGE! Worked
                                url += ElevatedSiteCol.AllWebs[webID].Lists[listID].DefaultViewUrl;
                                row["Title"] = "<a href=\"" + url + "\">" + row["Title"].ToString() + "</a>";
 
                                athrInd = row["Author"].ToString().IndexOf('#');
                                athrInd = athrInd + 1;
                                row["Author"] = row["Author"].ToString().Remove(0, athrInd);
 
                                asgnToInd = row["AssignedTo"].ToString().IndexOf('#');
                                asgnToInd = asgnToInd + 1;
                                row["AssignedTo"] = row["AssignedTo"].ToString().Remove(0, asgnToInd);
 
                                // Kinda Horable
                                if (row["PercentComplete"].ToString() != null && row["PercentComplete"].ToString().Contains("000") && row["PercentComplete"].ToString() != "0")
                                {
                                    row["PercentComplete"] = row["PercentComplete"].ToString().Replace("0000", "");
                                    row["PercentComplete"] = row["PercentComplete"].ToString().Replace(".", "") + "%";
                                    if (row["PercentComplete"].ToString().StartsWith("0"))
                                    {
                                        row["PercentComplete"] = row["PercentComplete"].ToString().Replace("0%", "%");
                                        row["PercentComplete"] = row["PercentComplete"].ToString().Remove(0, 1);
                                    }
                                }
 
                                if (row["PercentComplete"].ToString() == "0")
                                {
                                    row["PercentComplete"] = row["PercentComplete"].ToString() + "%";
                                }
 
                                row["modified"] = DateTime.Parse(row["modified"].ToString()).ToShortDateString() + "<br />" + DateTime.Parse(row["modified"].ToString()).ToShortTimeString();
 
                                row.AcceptChanges();
                            } 
                            #endregion
                                
                            // Bind the Data to the GridView
                            tasksCollection.DataSource = table;
                            tasksCollection.DataBind();
                            table.AcceptChanges();
                        }
 
                        catch (SPException SPEx)
                        {
                            Literal message = new Literal();
                            message.Text = SPEx.Message + "<br />" + SPEx.Source;
                            this.Controls.Add(message);
                        }
                    }
                }
            });
        }
 
    }
}

Open in new window

Avatar of 66866
66866
Flag of United States of America image

Hi buddy,
Didn't get much chance to peruse your code, however did you try using an SPGridview control instead of the regular ASP.Net gridview control?
Avatar of kvigor
kvigor

ASKER

That was an option I was going to pursue if this didn't materialize, and since the SPGridView is derived from the GridView Class/Control maybe it'll have the functionality/flexibility I need with Sorting...I'll try it.
Avatar of kvigor

ASKER

I changed the code to use SPGridView, however still no Sorting, the gain by doing this is that SPGridView now display better as WebPart. I believe that this has something to do with the page lifecycle...  I'm moving the logic around to test.
Can you post your code?
Avatar of kvigor

ASKER

Sure I'll do it when i get back to my workstation, but the code s/b posted already.
Avatar of kvigor

ASKER

Here's the code...
using System;
using System.Security.Principal;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebControls;
using System.Security.Permissions;
using System.Drawing;
using System.Globalization;
using System.DirectoryServices;
 
 
namespace ExecutiveTaskRollup
{
    public class TaskRollup : System.Web.UI.WebControls.WebParts.WebPart
    {
        SPGridView tasksCollection;
        string userName;
        string fullName;
        string searchFilter;
 
        protected string GetCurrentLoggedInUser()
        {
            searchFilter = "(samaccountname=";
 
            userName = HttpContext.Current.User.Identity.Name.ToString();
            userName = userName.Substring(4) + ")";
 
            searchFilter = searchFilter + userName;
            fullName = GetActiveADUsers("LDAP://adbox.company.com", searchFilter);
 
            return fullName;
        }
 
        public string GetActiveADUsers(string ldapString, string adSearchFilter)
        {
            DirectoryEntry de = new DirectoryEntry(ldapString, "domain\\user", "password");
            DirectorySearcher deSearch = new DirectorySearcher(de, adSearchFilter);
            // Passed in the constructor
            // deSearch.SearchRoot = de;
 
            // SubTree is the default, so really not required here. 
            deSearch.SearchScope = SearchScope.Subtree; //Including the sub OU's
 
            SearchResult result = deSearch.FindOne();
 
            string fullName = result.Properties["name"][0].ToString().Trim();
 
            return fullName;
        }
 
        protected override void CreateChildControls()
        {
            //base.CreateChildControls();
            tasksCollection = new SPGridView();
            tasksCollection.AllowSorting = true;
            tasksCollection.AutoGenerateColumns = false;
            tasksCollection.HeaderStyle.BorderStyle = BorderStyle.None;
            tasksCollection.BorderStyle = BorderStyle.None;
            tasksCollection.GridLines = GridLines.None;
            tasksCollection.CellPadding = 5;
            tasksCollection.CellSpacing = 0;
            tasksCollection.AlternatingRowStyle.BackColor = System.Drawing.Color.FromKnownColor(KnownColor.Lavender);
            tasksCollection.Sorting += new GridViewSortEventHandler(tasksCollection_Sorting);
 
            //Bind Columns Needed
            BoundField titleField = new BoundField();
            titleField.HtmlEncode = false;
            titleField.HeaderText = "Title";
            titleField.DataField = "Title";
            titleField.ShowHeader = true;
            tasksCollection.Columns.Add(titleField);
 
 
            BoundField priorityField = new BoundField();
            priorityField.HtmlEncode = false;
            priorityField.HeaderText = "Priority";
            priorityField.DataField = "Priority";
            tasksCollection.Columns.Add(priorityField);
 
            BoundField assignedToField = new BoundField();
            assignedToField.HtmlEncode = false;
            assignedToField.HeaderText = "Assigned To";
            assignedToField.DataField = "AssignedTo";
            tasksCollection.Columns.Add(assignedToField);
 
            BoundField statusField = new BoundField();
            statusField.HtmlEncode = false;
            statusField.HeaderText = "Status";
            statusField.DataField = "Status";
            tasksCollection.Columns.Add(statusField);
 
            BoundField percentCompleteField = new BoundField();
            percentCompleteField.HtmlEncode = false;
            percentCompleteField.HeaderText = "Percent Complete";
            percentCompleteField.DataField = "PercentComplete";
            tasksCollection.Columns.Add(percentCompleteField);
 
            BoundField modifiedField = new BoundField();
            modifiedField.HtmlEncode = false;
            modifiedField.HeaderText = "Modified";
            modifiedField.DataField = "Modified";
            modifiedField.ApplyFormatInEditMode = true;
            tasksCollection.Columns.Add(modifiedField);
 
            BoundField authorField = new BoundField();
            authorField.HtmlEncode = false;
            authorField.HeaderText = "Author" + fullName;
            authorField.DataField = "Author";
            tasksCollection.Columns.Add(authorField);
 
            Controls.Add(tasksCollection);
        }
 
        protected void tasksCollection_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dtAllowTableSorting = tasksCollection.DataSource as DataTable;
 
            if (dtAllowTableSorting != null)
            {
                DataView dvSortedView = new DataView(dtAllowTableSorting);
                dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
 
                tasksCollection.DataSource = dvSortedView;
                tasksCollection.DataBind();
            }
        }
 
        private string getSortDirectionString(System.Web.UI.WebControls.SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;
            if (sortDirection == System.Web.UI.WebControls.SortDirection.Ascending)
            {
                newSortDirection = "ASC";
            }
            else
            {
                newSortDirection = "DESC";
            }
 
            return newSortDirection;
        }
 
        protected override void OnPreRender(EventArgs e)
        {
            fullName = GetCurrentLoggedInUser();
            int athrInd, asgnToInd;
 
 
            SPSite siteCol = SPContext.Current.Site;
            SPWeb site = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedSiteCol = new SPSite(siteCol.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedSiteCol.OpenWeb(site.ID))
                    {
                        try
                        {
                            // Declaring Query Object
                            SPSiteDataQuery qry = new SPSiteDataQuery();
 
                            // Defining Query Object
                            // -switch these two on and off
                            //qry.Query = "<OrderBy><FieldRef Name='DueDate' Ascending='False' /><FieldRef Name='Title' /></OrderBy>";
                            //qry.Query = "<Where><Eq><FieldRef Name='Author' /><Value Type='Text'>" + fullName + "</Value></Eq></Where>";
                            qry.Query = "<Where><Or><Eq><FieldRef Name='AssignedTo' /><Value Type='Text'>" + fullName + "</Value></Eq><Eq><FieldRef Name='Author' /><Value Type='Text'>" + fullName + "</Value></Eq></Or></Where>";//Use this Query for Production
 
                            // Defining Columns to View
                            qry.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Priority' /><FieldRef Name='Status' /><FieldRef Name='PercentComplete' /><FieldRef Name='AssignedTo' /><FieldRef Name='Modified' /><FieldRef Name='Author' />";
 
                            // Setting List Type
                            qry.Lists = "<Lists ServerTemplate='107' />";
                            qry.Webs = "@<Webs Scope= 'SiteCollection' />";
 
                            //***First SPCONTEXT CHANGE! (Didn'WORK)
                            //DataTable table = SPContext.Current.Site.RootWeb.GetSiteData(qry);
                            DataTable table = ElevatedSiteCol.RootWeb.GetSiteData(qry);
 
                            #region                     //Format
                            foreach (DataRow row in table.Rows)
                            {
                                //Add hyyperlink to Title
                                Guid listID = new Guid(row["ListId"].ToString());
                                Guid webID = new Guid(row["WebId"].ToString());
 
                                string url = SPContext.Current.Site.Url;
                                //float dbl;
 
                                //***Second SPCONTEXT CHANGE! 
                                url += ElevatedSiteCol.AllWebs[webID].Lists[listID].DefaultViewUrl;
                                row["Title"] = "<a href=\"" + url + "\">" + row["Title"].ToString() + "</a>";
 
                                athrInd = row["Author"].ToString().IndexOf('#');
                                athrInd = athrInd + 1;
                                row["Author"] = row["Author"].ToString().Remove(0, athrInd);
 
                                asgnToInd = row["AssignedTo"].ToString().IndexOf('#');
                                asgnToInd = asgnToInd + 1;
                                row["AssignedTo"] = row["AssignedTo"].ToString().Remove(0, asgnToInd);
 
                                // Kinda Horable
                                if (row["PercentComplete"].ToString() != null && row["PercentComplete"].ToString().Contains("000") && row["PercentComplete"].ToString() != "0")
                                {
                                    row["PercentComplete"] = row["PercentComplete"].ToString().Replace("0000", "");
                                    row["PercentComplete"] = row["PercentComplete"].ToString().Replace(".", "") + "%";
                                    if (row["PercentComplete"].ToString().StartsWith("0"))
                                    {
                                        row["PercentComplete"] = row["PercentComplete"].ToString().Replace("0%", "%");
                                        row["PercentComplete"] = row["PercentComplete"].ToString().Remove(0, 1);
                                    }
 
                                }
                                if (row["PercentComplete"].ToString() == "0")
                                {
                                    row["PercentComplete"] = row["PercentComplete"].ToString() + "%";
                                }
 
                                row["modified"] = DateTime.Parse(row["modified"].ToString()).ToShortDateString() + "<br />" + DateTime.Parse(row["modified"].ToString()).ToShortTimeString();
 
                                row.AcceptChanges();
                            #endregion
                            }
 
                            // Bind the Data to the GridView
                            tasksCollection.DataSource = table;
                            tasksCollection.DataBind();
                            table.AcceptChanges();
                        }
 
                        catch (SPException SPEx)
                        {
                            Literal message = new Literal();
                            message.Text = SPEx.Message + "<br />" + SPEx.Source;
                            this.Controls.Add(message);
                        }
                    }
                }
            });
        }
    }
}

Open in new window

Check this solution and see if it fits your needs
http://www.codeproject.com/KB/sharepoint/SPGridviewWebpart.aspx
Avatar of kvigor

ASKER

I found that I needed to add the (boundField.SortExpression = "Column Description") line of code so the Column HeaderText would be clickable to respond to an event e.g. sort event".  

Since I've added that, it's now a matter of getting the tasksCollection_Sorting and getSortDirectionString logic written correctly, so it'll actually work,  I've seen it written 3 different ways,  I've written them as you see below, which is not working...
protected void tasksCollection_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dtAllowTableSorting = tasksCollection.DataSource as DataTable;
 
            if (dtAllowTableSorting != null)
            {
                DataView dvSortedView = new DataView(dtAllowTableSorting);
                dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
 
                tasksCollection.DataSource = dvSortedView;
                tasksCollection.DataBind();
            }
        }
       
private string getSortDirectionString(System.Web.UI.WebControls.SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;
            if (sortDirection == System.Web.UI.WebControls.SortDirection.Ascending)
            {
                newSortDirection = "ASC";
            }
            else
            {
                newSortDirection = "DESC";
            }
 
            return newSortDirection;
        }

Open in new window

I believe you need a SortExpression associated with each column to be sorted. This value is set to the column of data to be used for the order by (usually the field bound to that column).

If this doesn't work, you may want to try a static gridview in the code-infront because dynamic components don't always work well with data components.
Avatar of kvigor

ASKER

I've already added the sort expression but I'm not geting the sorting action when I click the column.
***Below is the updated version of my code***
using System;
using System.Security.Principal;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.WebControls;
using System.Security.Permissions;
using System.Drawing;
using System.Globalization;
using System.DirectoryServices;
 
 
namespace ExecutiveTaskRollup
{
    public class TaskRollup : System.Web.UI.WebControls.WebParts.WebPart
    {
        //DataView oView;
        SPGridView tasksCollection;
        DataTable table;
        string userName;
        string fullName;
        string searchFilter;
        
        protected string GetCurrentLoggedInUser()
        {
            searchFilter = "(samaccountname=";
 
            userName = HttpContext.Current.User.Identity.Name.ToString();
            userName = userName.Substring(4) + ")";
 
            searchFilter = searchFilter + userName;
            fullName = GetActiveADUsers("LDAP://www.company.com", searchFilter);
 
            return fullName;
        }
 
        public string GetActiveADUsers(string ldapString, string adSearchFilter)
        {
            DirectoryEntry de = new DirectoryEntry(ldapString, "domain\\user", "password");
            DirectorySearcher deSearch = new DirectorySearcher(de, adSearchFilter);
            // Passed in the constructor
            // deSearch.SearchRoot = de;
 
            // SubTree is the default, so really not required here. 
            deSearch.SearchScope = SearchScope.Subtree; //Including the sub OU's
 
            SearchResult result = deSearch.FindOne();
 
            string fullName = result.Properties["name"][0].ToString().Trim();
 
            return fullName;
        }
 
        protected override void CreateChildControls()
        {
            //base.CreateChildControls();
           
            tasksCollection = new SPGridView();
            
            tasksCollection.AutoGenerateColumns = false;
            tasksCollection.HeaderStyle.BorderStyle = BorderStyle.None;
            tasksCollection.BorderStyle = BorderStyle.None;
            tasksCollection.GridLines = GridLines.None;
            tasksCollection.CellPadding = 5;
            tasksCollection.CellSpacing = 0;
            tasksCollection.AlternatingRowStyle.BackColor = System.Drawing.Color.FromKnownColor(KnownColor.Lavender);
            tasksCollection.AllowSorting = true;
            tasksCollection.Sorting += new GridViewSortEventHandler(tasksCollection_Sorting);
 
            //Bind Columns Needed
            BoundField titleField = new BoundField();
            titleField.HtmlEncode = false;
            titleField.HeaderText = "Title";
            titleField.DataField = "Title";
            titleField.SortExpression = "Title";
            titleField.ShowHeader = true;
            tasksCollection.Columns.Add(titleField);
            
 
            BoundField priorityField = new BoundField();
            priorityField.HtmlEncode = false;
            priorityField.HeaderText = "Priority";
            priorityField.DataField = "Priority";
            priorityField.SortExpression = "Priority";
            tasksCollection.Columns.Add(priorityField);
 
            BoundField assignedToField = new BoundField();
            assignedToField.HtmlEncode = false;
            assignedToField.HeaderText = "Assigned To";
            assignedToField.DataField = "AssignedTo";
            assignedToField.SortExpression = "AssignedTo";
            tasksCollection.Columns.Add(assignedToField);
 
            BoundField statusField = new BoundField();
            statusField.HtmlEncode = false;
            statusField.HeaderText = "Status";
            statusField.DataField = "Status";
            statusField.SortExpression = "Status";
            tasksCollection.Columns.Add(statusField);
 
            BoundField percentCompleteField = new BoundField();
            percentCompleteField.HtmlEncode = false;
            percentCompleteField.HeaderText = "Percent Complete";
            percentCompleteField.DataField = "PercentComplete";
            percentCompleteField.SortExpression = "PercentComplete";
            tasksCollection.Columns.Add(percentCompleteField);
 
            BoundField modifiedField = new BoundField();
            modifiedField.HtmlEncode = false;
            modifiedField.HeaderText = "Modified";
            modifiedField.DataField = "Modified";
            modifiedField.SortExpression = "Modified";
            modifiedField.ApplyFormatInEditMode = true;
            tasksCollection.Columns.Add(modifiedField);
 
            BoundField authorField = new BoundField();
            authorField.HtmlEncode = false;
            authorField.HeaderText = "Author" + fullName;
            authorField.DataField = "Author";
            authorField.SortExpression = "Author";
            tasksCollection.Columns.Add(authorField);
 
            Controls.Add(tasksCollection);
            tasksCollection.DataBind();
 
            base.CreateChildControls();
        }
 
        protected void tasksCollection_Sorting(object sender, GridViewSortEventArgs e)
        {
            //The as operator is used to perform conversions between compatible types.
            DataTable dtAllowTableSorting = tasksCollection.DataSource as DataTable;
 
            if (dtAllowTableSorting != null)
            {
                DataView dvSortedView = new DataView(dtAllowTableSorting);
                dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
 
                tasksCollection.DataSource = dvSortedView;
                tasksCollection.DataBind();
            }
        }
 
        private string getSortDirectionString(System.Web.UI.WebControls.SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;
 
            if (sortDirection == System.Web.UI.WebControls.SortDirection.Ascending)
            {
                newSortDirection = "ASC";
            }
            else
            {
                newSortDirection = "DESC";
            }
 
            return newSortDirection;
        }
 
        protected override void OnPreRender(EventArgs e)
        {
            fullName = GetCurrentLoggedInUser();
            int athrInd, asgnToInd;
 
 
            SPSite siteCol = SPContext.Current.Site;
            SPWeb site = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedSiteCol = new SPSite(siteCol.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedSiteCol.OpenWeb(site.ID))
                    {
                        try
                        {
                            // Declaring Query Object
                            SPSiteDataQuery qry = new SPSiteDataQuery();
 
                            // Defining Query Object
                            // -switch these two on and off
                            //qry.Query = "<OrderBy><FieldRef Name='DueDate' Ascending='False' /><FieldRef Name='Title' /></OrderBy>";
                            //qry.Query = "<Where><Eq><FieldRef Name='Author' /><Value Type='Text'>" + fullName + "</Value></Eq></Where>";
                            qry.Query = "<Where><Or><Eq><FieldRef Name='AssignedTo' /><Value Type='Text'>" + fullName + "</Value></Eq><Eq><FieldRef Name='Author' /><Value Type='Text'>" + fullName + "</Value></Eq></Or></Where>";//Use this Query for Production
 
                            // Defining Columns to View
                            qry.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Priority' /><FieldRef Name='Status' /><FieldRef Name='PercentComplete' /><FieldRef Name='AssignedTo' /><FieldRef Name='Modified' /><FieldRef Name='Author' />";
 
                            // Setting List Type
                            qry.Lists = "<Lists ServerTemplate='107' />";
                            qry.Webs = "@<Webs Scope= 'SiteCollection' />";
 
                            //***First SPCONTEXT CHANGE! (Didn'WORK)
                            //DataTable table = SPContext.Current.Site.RootWeb.GetSiteData(qry);
                            table = ElevatedSiteCol.RootWeb.GetSiteData(qry);
 
#region                     //Format
                            foreach (DataRow row in table.Rows)
                            {
                                //Add hyperlink to Title
                                Guid listID = new Guid(row["ListId"].ToString());
                                Guid webID = new Guid(row["WebId"].ToString());
 
                                string url = SPContext.Current.Site.Url;
                                //float dbl;
 
                                //***Second SPCONTEXT CHANGE! 
                                url += ElevatedSiteCol.AllWebs[webID].Lists[listID].DefaultViewUrl;
                                row["Title"] = "<a href=\"" + url + "\">" + row["Title"].ToString() + "</a>";
 
                                athrInd = row["Author"].ToString().IndexOf('#');
                                athrInd = athrInd + 1;
                                row["Author"] = row["Author"].ToString().Remove(0, athrInd);
 
                                asgnToInd = row["AssignedTo"].ToString().IndexOf('#');
                                asgnToInd = asgnToInd + 1;
                                row["AssignedTo"] = row["AssignedTo"].ToString().Remove(0, asgnToInd);
 
                        // Kinda Horable
                                if (row["PercentComplete"].ToString() != null && row["PercentComplete"].ToString().Contains("000") && row["PercentComplete"].ToString() != "0")
                                {
                                    row["PercentComplete"] = row["PercentComplete"].ToString().Replace("0000", "");
                                    row["PercentComplete"] = row["PercentComplete"].ToString().Replace(".", "") + "%";
                                    if (row["PercentComplete"].ToString().StartsWith("0"))
                                    {
                                        row["PercentComplete"] = row["PercentComplete"].ToString().Replace("0%", "%");
                                        row["PercentComplete"] = row["PercentComplete"].ToString().Remove(0, 1);
                                    }
 
                                }
                                if (row["PercentComplete"].ToString() == "0")
                                {
                                    row["PercentComplete"] = row["PercentComplete"].ToString() + "%";
                                }
 
                                row["modified"] = DateTime.Parse(row["modified"].ToString()).ToShortDateString() + "<br />" + DateTime.Parse(row["modified"].ToString()).ToShortTimeString();
 
                                row.AcceptChanges();
#endregion
                            }
                            
                            // Bind the Data to the GridView
                            tasksCollection.DataSource = table;
                            tasksCollection.DataBind();
                            table.AcceptChanges();
                        }
 
                        catch (SPException SPEx)
                        {
                            Literal message = new Literal();
                            message.Text = SPEx.Message + "<br />" + SPEx.Source;
                            this.Controls.Add(message);
                        }
                    }
                }
            });
        }
    }
}

Open in new window

Avatar of kvigor

ASKER

Still working on it.
Avatar of kvigor

ASKER

OK, If there's anyone out there that knows about SharePoint WSPs (Web Solution Packages), the WebPart LifeCycle, and how ViewState works with SharePoint WebParts then please respond to this thread.
Avatar of kvigor

ASKER

I believe this has something to do with View_State... I believe I'm getting closer...
Avatar of kvigor

ASKER

I found a solution that's working and currently deployed in my Farm so I'll review the code and let all who cares know.
Avatar of kvigor

ASKER

I'll post the answer to this question so leave it open.
ASKER CERTIFIED SOLUTION
Avatar of kvigor
kvigor

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial