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

kvigorAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

66866Commented:
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?
0
kvigorAuthor Commented:
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.
0
kvigorAuthor Commented:
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.
0
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

66866Commented:
Can you post your code?
0
kvigorAuthor Commented:
Sure I'll do it when i get back to my workstation, but the code s/b posted already.
0
kvigorAuthor Commented:
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

0
66866Commented:
Check this solution and see if it fits your needs
http://www.codeproject.com/KB/sharepoint/SPGridviewWebpart.aspx
0
kvigorAuthor Commented:
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

0
strickddCommented:
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.
0
kvigorAuthor Commented:
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

0
kvigorAuthor Commented:
Still working on it.
0
kvigorAuthor Commented:
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.
0
kvigorAuthor Commented:
I believe this has something to do with View_State... I believe I'm getting closer...
0
kvigorAuthor Commented:
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.
0
kvigorAuthor Commented:
I'll post the answer to this question so leave it open.
0
kvigorAuthor Commented:
The solution to this is was that my existing sorting code was in the wrong code block.  It should have been in the createchildcontols block... see code example below.
protected override void CreateChildControls()
{
   //Sorting Logic here
} 

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.