473,685 Members | 3,005 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sort GridView without DataSourceContr ol

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 DataSourceContr ol 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 5236
Hi Peter,

Please try following code:

Aspx:

<asp:GridView PageSize="4" ID="gridView" AllowPaging="tr ue"
AllowSorting="t rue"

OnPageIndexChan ging="gridView_ PageIndexChangi ng"
OnSorting="grid View_Sorting"

runat="server" />

Aspx.cs:

using System;
using System.Configur ation;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.H tmlControls;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Xml.Linq ;
using System.Collecti ons;
using System.Collecti ons.Generic;
using System.Reflecti on;

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

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

set
{
ViewState["SortDirect ion"] = value;
}

}

private string GridViewSortExp ression
{

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

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

}


protected void gridView_PageIn dexChanging(obj ect sender,
GridViewPageEve ntArgs e)
{

gridView.DataSo urce = SortList(gridVi ew.DataSource as
List<object>,tr ue);

gridView.PageIn dex = e.NewPageIndex;

gridView.DataBi nd();

}

protected List<objectSort List(List<objec tdata, bool
isPageIndexChan ging)
{
List<objectresu lt = new List<object>();
if (data != null)
{

if (GridViewSortEx pression != string.Empty)
{
if(data.Count>0 )
{
PropertyInfo[] propertys
=data[0].GetType().GetP roperties();
foreach (PropertyInfo p in propertys)
{
if (p.Name == GridViewSortExp ression)
{

if (GridViewSortDi rection == "ASC")
{
if (isPageIndexCha nging)
{
result = data.OrderByDes cending(key
=p.GetValue(key , null)).ToList() ;
}
else
{
result = data.OrderBy(ke y =>
p.GetValue(key, null)).ToList() ;
GridViewSortDir ection = "DESC";
}

}
else
{
if (isPageIndexCha nging)
{
result = data.OrderBy(ke y =>
p.GetValue(key, null)).ToList() ;
}
else
{
result = data.OrderByDes cending(key
=p.GetValue(key , null)).ToList() ;
GridViewSortDir ection = "ASC";
}

}

break;

}
}

}

}

}
_sorted = true;
return result;

}

protected void gridView_Sortin g(object sender, GridViewSortEve ntArgs e)
{

GridViewSortExp ression = e.SortExpressio n;

int pageIndex = gridView.PageIn dex;

gridView.DataSo urce = SortList(gridVi ew.DataSource as List<object>,
false);

gridView.DataBi nd();

gridView.PageIn dex = pageIndex;

}
static Random r=new Random();
protected void Page_Load(objec t sender, EventArgs e)
{
if (!IsPostBack)
{
this.GridViewSo rtExpression = "ID";
}
List<objectlist = new List<object>();
for (int i = 0; i < 10; i++)
{
list.Add(new Customer() { ID = i, Name = "Test"});
}
this.gridView.D ataSource = list;
this.gridView.D ataBind();

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

gridView.DataBi nd();
}
}
}

Above code requires .NET Framework 3.5.

Though it can work I would strongly recommend you use ObjectDataSourc e. It
has built-in sorting support and is more efficient than manually binding
GridView.You can learn how to use ObjectDataSourc e 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****@microsof t.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 DataSourceContr ol
| 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.publi c.dotnet.framew ork.aspnet
| NNTP-Posting-Host: CPE-72-129-145-58.new.res.rr.c om 72.129.145.58
| Path: TK2MSFTNGHUB02. phx.gbl!TK2MSFT NGP01.phx.gbl!T K2MSFTNGP03.phx .gbl
| Xref: TK2MSFTNGHUB02. phx.gbl
microsoft.publi c.dotnet.framew ork.aspnet:7878 9
| X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.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 DataSourceContr ol 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 ObjectDataSourc e, 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.m icrosoft.comwro te in message
news:qj******** ********@TK2MSF TNGHUB02.phx.gb l...
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************ **@TK2MSFTNGHUB 02.phx.gbl>
| Subject: Re: Sort GridView without DataSourceContr ol
| 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.publi c.dotnet.framew ork.aspnet
| NNTP-Posting-Host: cpe-72-129-145-58.new.res.rr.c om 72.129.145.58
| Path: TK2MSFTNGHUB02. phx.gbl!TK2MSFT NGP01.phx.gbl!T K2MSFTNGP06.phx .gbl
| Xref: TK2MSFTNGHUB02. phx.gbl
microsoft.publi c.dotnet.framew ork.aspnet:7892 6
| X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.aspnet
|
| Thank you for your help!
|
| I took your advices and used ObjectDataSourc e, 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.m icrosoft.comwro te in message
| news:qj******** ********@TK2MSF TNGHUB02.phx.gb l...
| 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
18537
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" ConnectionString="<%$ ConnectionStrings:cnnSQL_Connect %>" Runat="server"> <SelectParameters> <asp:Parameter Type="String" DefaultValue="FindWebDocAll"
7
14806
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 want to look at that data and filter it based on what is in it. I know that this could have been done with data sets and data views in asp.net 1.1 but how is this done now in asp.net 2.0?
7
5465
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 loop through the filtered GridView to identify the selected rows and assemble some XML to be sent to a stored proc. The problem I have is that when looping through the GridView, it doesn't
4
13485
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. I just set the GridView.DataSource once, and call DataBind(); I'd like to drive the application from the GridView control, by including command buttons that allow editing of the data. Starting out simple, I have a DataTable with a boolean...
2
2299
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 vb -- thanks (as always) some day i''m gona pay this forum back for all the help i''m getting kes
13
42028
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 footer template has an commandbutton with the commandname set to 'Insert'. Both buttons cause postback, however the RowCommand event does not fire. How can I get the rowcommand to fire?
13
10775
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 no simple solution. I do not believe ASP.Net team took this, sort of, innovative approach and left no way out. Could anybody advise?
3
2188
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
12564
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 Page_Load(object sender, EventArgs e) { ObjectDataSource ods = new ObjectDataSource("MyTestTableAdapter",
0
8577
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8926
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8761
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7589
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5792
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.