Sort GridView without DataSourceControl

A

Allen Chen [MSFT]

Hi Peter,

Please try following code:

Aspx:

<asp:GridView PageSize="4" ID="gridView" AllowPaging="true"
AllowSorting="true"

OnPageIndexChanging="gridView_PageIndexChanging"
OnSorting="gridView_Sorting"

runat="server" />

Aspx.cs:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

public class Customer {
public int ID { get; set; }
public string Name { get; set; }
}
public partial class _Default : System.Web.UI.Page
{
bool _sorted = false;
private string GridViewSortDirection
{

get
{
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = "ASC";
}
return ViewState["SortDirection"].ToString();
}

set
{
ViewState["SortDirection"] = value;
}

}



private string GridViewSortExpression
{

get { return ViewState["SortExpression"] as string ?? string.Empty;
}

set { ViewState["SortExpression"] = value; }

}






protected void gridView_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{

gridView.DataSource = SortList(gridView.DataSource as
List<object>,true);

gridView.PageIndex = e.NewPageIndex;

gridView.DataBind();

}



protected List<object> SortList(List<object> data, bool
isPageIndexChanging)
{
List<object> result = new List<object>();
if (data != null)
{



if (GridViewSortExpression != string.Empty)
{
if(data.Count>0)
{
PropertyInfo[] propertys
=data[0].GetType().GetProperties();
foreach (PropertyInfo p in propertys)
{
if (p.Name == GridViewSortExpression)
{



if (GridViewSortDirection == "ASC")
{
if (isPageIndexChanging)
{
result = data.OrderByDescending(key
=> p.GetValue(key, null)).ToList();
}
else
{
result = data.OrderBy(key =>
p.GetValue(key, null)).ToList();
GridViewSortDirection = "DESC";
}

}
else
{
if (isPageIndexChanging)
{
result = data.OrderBy(key =>
p.GetValue(key, null)).ToList();
}
else
{
result = data.OrderByDescending(key
=> p.GetValue(key, null)).ToList();
GridViewSortDirection = "ASC";
}

}

break;

}
}



}

}

}
_sorted = true;
return result;

}



protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{

GridViewSortExpression = e.SortExpression;

int pageIndex = gridView.PageIndex;

gridView.DataSource = SortList(gridView.DataSource as List<object>,
false);

gridView.DataBind();

gridView.PageIndex = pageIndex;

}
static Random r=new Random();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GridViewSortExpression = "ID";
}
List<object> list = new List<object>();
for (int i = 0; i < 10; i++)
{
list.Add(new Customer() { ID = i, Name = "Test"});
}
this.gridView.DataSource = list;
this.gridView.DataBind();

}
protected void Page_PreRender(object sender, EventArgs e)
{
if (IsPostBack && !_sorted)
{
gridView.DataSource = SortList(gridView.DataSource as
List<object>, true);

gridView.DataBind();
}
}
}

Above code requires .NET Framework 3.5.

Though it can work I would strongly recommend you use ObjectDataSource. It
has built-in sorting support and is more efficient than manually binding
GridView.You can learn how to use ObjectDataSource from here:

http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/objectdatas
ource.aspx

Please let me know if my code works and feel free to ask if you need
further assistance.

Regards,
Allen Chen
Microsoft Online Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subscriptions/aa948868.aspx#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/default.aspx?target=assistance&ln=en-us.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.



--------------------
| From: "Peter" <[email protected]>
| Subject: Sort GridView without DataSourceControl
| Date: Mon, 27 Oct 2008 23:45:38 -0500
| Lines: 10
| X-Priority: 3
| X-MSMail-Priority: Normal
| X-Newsreader: Microsoft Outlook Express 6.00.2900.5512
| X-RFC2646: Format=Flowed; Original
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5579
| Message-ID: <#[email protected]>
| Newsgroups: microsoft.public.dotnet.framework.aspnet
| NNTP-Posting-Host: CPE-72-129-145-58.new.res.rr.com 72.129.145.58
| Path: TK2MSFTNGHUB02.phx.gbl!TK2MSFTNGP01.phx.gbl!TK2MSFTNGP03.phx.gbl
| Xref: TK2MSFTNGHUB02.phx.gbl
microsoft.public.dotnet.framework.aspnet:78789
| X-Tomcat-NG: microsoft.public.dotnet.framework.aspnet
|
| I have a GridView which is populated by List<ofObjects>
| Does anyone have example of how to sort the columns of this GridView?
|
| I have found examples without DataSourceControl but these use DataTable,
I
| am using List of Objects.
|
| Here's one example:
|
http://ryanolshan.com/technology/gridview-without-datasourcecontrol-datasour
ce/
|
|
|
 
P

Peter

Thank you for your help!

I took your advices and used ObjectDataSource, but it's too much of a pain,
for example you can't use Objects and use Filtering, you have to create your
own filtering. So instead of spending more time on this I just went back to
SqlDataSource - for now I am using MS SQL anyway.
 
A

Allen Chen [MSFT]

Hi Peter,

It's also good to use SqlDataSource. Do you have any further questions? If
you have please do let me know.

Regards,
Allen Chen
Microsoft Online Support

--------------------
| From: "Peter" <[email protected]>
| References: <#[email protected]>
<qjh#[email protected]>
| Subject: Re: Sort GridView without DataSourceControl
| Date: Wed, 29 Oct 2008 22:35:20 -0500
| Lines: 16
| X-Priority: 3
| X-MSMail-Priority: Normal
| X-Newsreader: Microsoft Outlook Express 6.00.2900.5512
| X-RFC2646: Format=Flowed; Original
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.5579
| Message-ID: <#[email protected]>
| Newsgroups: microsoft.public.dotnet.framework.aspnet
| NNTP-Posting-Host: cpe-72-129-145-58.new.res.rr.com 72.129.145.58
| Path: TK2MSFTNGHUB02.phx.gbl!TK2MSFTNGP01.phx.gbl!TK2MSFTNGP06.phx.gbl
| Xref: TK2MSFTNGHUB02.phx.gbl
microsoft.public.dotnet.framework.aspnet:78926
| X-Tomcat-NG: microsoft.public.dotnet.framework.aspnet
|
| Thank you for your help!
|
| I took your advices and used ObjectDataSource, but it's too much of a
pain,
| for example you can't use Objects and use Filtering, you have to create
your
| own filtering. So instead of spending more time on this I just went back
to
| SqlDataSource - for now I am using MS SQL anyway.
|
|
| | > Hi Peter,
| >
| > Please try following code:
| >
|
|
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top