473,246 Members | 1,204 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,246 software developers and data experts.

Sort GridView Bound to Collection of Objects


I've been experimenting with the ASP.Net GridView and encountered some
interesting issues that I thought I would share. I have a page that
loads a GridView with a generic collection of objects. For the purposes
of this discussion, the objects define a Customer, and have an id and a

I want to sort these customers by id or by name in ascending and
descending order. Here is what I did to make it work.

First I added a GridView to an ASP.Net Page.

<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
<asp:HyperLinkField "DataNavigateUrlFields="CustomerId"
DataTextField="CustomerId" HeaderText="Id"
<asp:HyperLinkField "DataNavigateUrlFields="CustomerId"
DataTextField="CustomerName" HeaderText="Name"

Add your own style and formatting. Notice that I use the object's
public properties in the DataNavigateUrlFields, DataTextField and
SortExpression attributes.

Also, I did not set EnableSortingAndPagingCallbacks to true because
this caused my callbacks to stop working.

Now, I have a collection called Customers which inherits List(Of
Customer). I added an overloaded public method called Sort, which uses
a CaseInsensitiveComparer, which I will show later. The Sort methods

Public Overloads Sub Sort(ByVal strPropertyName As String, ByVal
strDirection As String)
Dim arSortedList As New ArrayList
For Each item As Customer In Me
arSortedList.Sort(New CaseInsensitiveComparer(Of
Customer)(strPropertyName, strDirection)
Dim position As Integer
Dim temp As Customer
Dim oSortedCustomer As Customer
Dim oUnsortedCustomer As Customer
For i As Integer = 0 To arSortedList.Count - 1
oSortedCustomer = CType(arSortedList(i), Customer)
For position = 0 To Count - 1
oUnsortedCustomer = CType(Item(position), Customer)
If oSortedCustomer.CustomerId = oUnsortedCustomer.CustomerId Then
Exit For
End If
If position <i And position <Count Then
temp = Item(i)
Item(i) = Item(position)
Item(position) = temp
End If
End Sub

Here is the generic CaseInsensitiveComparer class.

Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Reflection

Public Class CaseInsensitiveComparer(Of T)
Implements IComparer

Private _oComparer As New CaseInsensitiveComparer
Private _strDirection As String
Private _oPropInfo As PropertyInfo

Public Sub New(ByVal strPropertyName As String, ByVal strDirection As
_oPropInfo = GetType(T).GetProperty(strPropertyName)
If _oPropInfo Is Nothing Then
Throw New ArgumentException("Property not found")
End If
_strDirection = strDirection.ToLower()
End Sub

Public Function Compare(ByVal x As Object, ByVal y As Object) As
Integer Implements System.Collections.IComparer.Compare
Dim oX As T
Dim oY As T
oX = CType(x, T)
oY = CType(y, T)
If _strDirection = "asc" Then
Return _oComparer.Compare(_oPropInfo.GetValue(oX, Nothing),
_oPropInfo.GetValue(oY, Nothing))
Return _oComparer.Compare(_oPropInfo.GetValue(oY, Nothing),
_oPropInfo.GetValue(oX, Nothing))
End If
End Function

Now, my OnSorting event in the ASP page follows.

Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As
GridViewSortEventArgs) Handles GridView1.Sorting
Dim oCustomers As Customers
oCustomers = New Customers
If oCustomers.Load() Then
If String.IsNullOrEmpty(ViewState(e.SortExpression)) Then
ViewState(e.SortExpression) = "asc"
End If
If ViewState(e.SortExpression) = "asc" Then
ViewState(e.SortExpression) = "desc" Else ViewState(e.SortExpression) =
oCustomers.Sort(e.SortExpression, ViewState(e.SortExpression))
GridView1.DataSource = oCustomers
End If
Catch ex As Exception
lblError.Text = ex.Message
End Try
End Sub

I track the sorting in view state because it has been reported that the
event argument doesn't reflect the sort direction correctly.

Comments are welcome.

Jan 17 '07 #1
0 4802

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

Similar topics

by: Giorgio | last post by:
It seems that the ASP.NET Microsoft team didn't think about this!! The profilemanager class has the following methods: - DeleteInactiveProfiles. Enables you to delete all profiles older...
by: Brien King | last post by:
I am binding to a collection of Business Objects in a GridView (Windows App, ..NET 2.0). In my Business Object I have a Property that is an ENUM. I want a Drop down box in the Grid that is...
by: Rob Roberts | last post by:
I have a GridView that is bound to a collection of DateTimes (i.e. - Collection<DateTime>). I have a BoundField in the GridView, and its DataField is set to the DateTime's Date property, and the...
by: hazz | last post by:
given <asp:BoundField DataField="ID" SortExpression="ID" visible = "True"></asp:BoundField> how can I access this ID field from within a button click event. I had bound a collection of busiess...
by: mazdotnet | last post by:
Hi everyone, I know when you enable paging in a datagrid the entire data is read but only the data that you want is displayed to the end user. Has this changed for Gridview? So if you have 10000...
by: BartMan | last post by:
Greetings, I have a gridview which is sitting on a multi view control (witin a view), and it is bound to a dataset which I dynamically apply to the control within asp.net page. The problem is...
by: r.hein | last post by:
I've got a middle tier data object that I'm binding a gridview to, and I'm having some problems with the check box, and having it enabled. Let'd start with the middle tier object (and the...
by: Dev147 | last post by:
I need to dynamically create a GridView that contains a variable number of columns that must be bound to an underlying collection in an entity class. These columns represent days from a specified...
by: jenka1980 | last post by:
What is the best way to correspond SkinId in GridView to the data which bound to it ? I have dataset which I bound to a GridView. Dataset contains a table where part of rows are title rows....
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

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.