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

Hi,

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
name.

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"
AutoGenerateColumns="False">
<Columns>
<asp:HyperLinkField "DataNavigateUrlFields="CustomerId"
DataNavigationUrlFormatString="~/YourScript.aspx?CustomerId={0}"
DataTextField="CustomerId" HeaderText="Id"
SortExpression="CustomerId"></asp:HyperLinkField>
<asp:HyperLinkField "DataNavigateUrlFields="CustomerId"
DataNavigationUrlFormatString="~/YourScript.aspx?CustomerId={0}"
DataTextField="CustomerName" HeaderText="Name"
SortExpression="CustomerName"></asp:HyperLinkField>
</Columns>
</asp:GridView>

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
follows.

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.Add(item)
Next
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
Next
If position <i And position <Count Then
temp = Item(i)
Item(i) = Item(position)
Item(position) = temp
End If
Next
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
String)
_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))
Else
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
Try
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) =
"asc"
oCustomers.Sort(e.SortExpression, ViewState(e.SortExpression))
GridView1.DataSource = oCustomers
GridView1.DataBind()
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

0
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...
1
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...
2
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...
0
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...
3
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...
3
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...
3
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...
1
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...
0
jenka1980
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....
2
isladogs
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...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
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...
0
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...
0
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...
0
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 =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
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...
0
isladogs
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.