Solved

GridView Sorting in SharePoint WebPart: Sorting not working

Posted on 2009-07-08
20
2,362 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
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
 
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

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

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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

910 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

23 Experts available now in Live!

Get 1:1 Help Now