473,385 Members | 1,355 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Sort GridView without DataSourceControl

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/gri...ol-datasource/
Oct 28 '08 #1
3 5207
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<objectSortList(List<objectdata, bool
isPageIndexChanging)
{
List<objectresult = 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<objectlist = 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/QuickStar...ta/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:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subs...#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/...tance&ln=en-us.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
| From: "Peter" <cz****@nospam.nospam>
| 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: <#w*************@TK2MSFTNGP03.phx.gbl>
| 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!TK2MSF TNGP03.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/gri...ntrol-datasour
ce/
|
|
|

Oct 28 '08 #2
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.
"Allen Chen [MSFT]" <v-******@online.microsoft.comwrote in message
news:qj****************@TK2MSFTNGHUB02.phx.gbl...
Hi Peter,

Please try following code:

Oct 30 '08 #3
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" <cz****@nospam.nospam>
| References: <#w*************@TK2MSFTNGP03.phx.gbl>
<qj**************@TK2MSFTNGHUB02.phx.gbl>
| 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: <#B*************@TK2MSFTNGP06.phx.gbl>
| 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!TK2MSF TNGP06.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.
|
|
| "Allen Chen [MSFT]" <v-******@online.microsoft.comwrote in message
| news:qj****************@TK2MSFTNGHUB02.phx.gbl...
| Hi Peter,
| >
| Please try following code:
| >
|
|
|

Oct 30 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: sck10 | last post by:
Hello, I have a GridView that is using the following to connect to a SQL Server 2000 stored procedure: <asp:SqlDataSource ID="dsWebDocList" SelectCommand="sp_web_WebDocument"...
7
by: | last post by:
Hello, Does anyone have an idea on how I can filter the data in the gridview control that was returned by an sql query? I have a gridview that works fine when I populate it with data. Now I...
7
by: Ken | last post by:
Hi All - I have a filtered GridView. This GridView has a check box in the first column. This check box is used to identify specific rows for delete operations. On the button click event I...
4
by: Jim Katz | last post by:
I have an application that updates a strongly typed data set at run time. I'd like to dynamically create a table that connects to a run time data table. For displaying the data, this works well. ...
2
by: WebBuilder451 | last post by:
I have a grid view with a filter based on a dropdown list. when i select a page on the gridview the filter gets dropped. What is the correct way to handle paging when using a filter? asp.net 2.0...
13
by: AG | last post by:
I have a gridview that I bind to a List(of Type) at runtime. Not using a datasource control. The gridview has a template column with an imagebutton whose commandname is set to 'Delete'. The...
13
by: Tomasz Jastrzebski | last post by:
Helo All, The problem: GridView control does not render at all (header/footer) when the data source is empty. I have seen a similar question posted already, but I just can not believe there is...
3
by: Marc Grutte | last post by:
Hi I am trying to bind a custom datasource to a gridview whilst paging is enabled. What is missing in this code to make the paging + binding work? thanks M <%@ Page Language="VB" %>
4
by: Tomasz | last post by:
Hello Developers, Here is interesting problem I just came across: how do I wire a GridView control programmatically? Here is my sample code using Object Data Source: protected void...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.