Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

GridView Sorting in SharePoint WebPart: Sorting not working

Posted on 2009-07-08
20
Medium Priority
?
2,424 Views
Last Modified: 2012-06-27
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

0
Comment
Question by:kvigor
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 12
  • 3
20 Comments
 
LVL 21

Expert Comment

by:66866
ID: 24813435
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
 

Author Comment

by:kvigor
ID: 24814121
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
 

Author Comment

by:kvigor
ID: 24815882
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 21

Expert Comment

by:66866
ID: 24816176
Can you post your code?
0
 

Author Comment

by:kvigor
ID: 24816536
Sure I'll do it when i get back to my workstation, but the code s/b posted already.
0
 

Author Comment

by:kvigor
ID: 24817402
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
 
LVL 21

Expert Comment

by:66866
ID: 24823593
Check this solution and see if it fits your needs
http://www.codeproject.com/KB/sharepoint/SPGridviewWebpart.aspx
0
 

Author Comment

by:kvigor
ID: 24870084
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
 
LVL 28

Expert Comment

by:strickdd
ID: 24987780
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
 

Author Comment

by:kvigor
ID: 25018008
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
 

Author Comment

by:kvigor
ID: 25099363
Still working on it.
0
 

Author Comment

by:kvigor
ID: 25152413
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
 

Author Comment

by:kvigor
ID: 25251819
I believe this has something to do with View_State... I believe I'm getting closer...
0
 

Author Comment

by:kvigor
ID: 25283843
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
 

Author Comment

by:kvigor
ID: 25301139
I'll post the answer to this question so leave it open.
0
 

Accepted Solution

by:
kvigor earned 0 total points
ID: 25384714
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

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question