Solved

GridView Sorting in SharePoint WebPart: Sorting not working

Posted on 2009-07-08
20
2,345 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
  • 12
  • 3
20 Comments
 
LVL 21

Expert Comment

by:66866
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 21

Expert Comment

by:66866
Comment Utility
Can you post your code?
0
 

Author Comment

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

Author Comment

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

Author Comment

by:kvigor
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 28

Expert Comment

by:strickdd
Comment Utility
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
Comment Utility
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
Comment Utility
Still working on it.
0
 

Author Comment

by:kvigor
Comment Utility
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
Comment Utility
I believe this has something to do with View_State... I believe I'm getting closer...
0
 

Author Comment

by:kvigor
Comment Utility
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
Comment Utility
I'll post the answer to this question so leave it open.
0
 

Accepted Solution

by:
kvigor earned 0 total points
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
comparing string in C# 3 32
Editing XSL files, 2 18
Re-position the objects 7 46
Format column on datatable 7 14
We had a requirement to extract data from a SharePoint 2010 Customer List into a CSV file and then place the CSV file into a directory on the network so that the file could be consumed by an AS400 system. I will share in Part 1 how to Extract the Da…
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!
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

744 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now