473,387 Members | 1,493 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,387 developers and data experts.

How to add sortable functionallity to the DataTable...

Aimee Bailey
197 Expert 100+
In work today I was asked weather it was possible to sort a DataTable via column index, so while looking through the DataTable method list, I was surprised to find nothing but the simple DataTable.Select method.

Luckily in .Net we can inherit classes, so it is not hard to implement a custom sort feature. here is how I did this:

Expand|Select|Wrap|Line Numbers
  1. Public Class SortableDataTable
  2.        Inherits DataTable
  3.  
  4.     Public Sub Sort(ByVal columnIndex As Integer, _
  5.                     ByVal direction As dDir)
  6.         Dim result As New List(Of DataRow)
  7.         Select Case direction
  8.             Case dDir.Ascending
  9.                 Dim v = From r In Me.Rows _
  10.                         Order By r(columnIndex) _
  11.                         Ascending
  12.                 For Each row In v
  13.                     Dim nr As DataRow = Me.NewRow
  14.                     nr.ItemArray = row.ItemArray.Clone
  15.                     result.Add(nr)
  16.                 Next
  17.             Case dDir.Descending
  18.                 Dim v = From r In Me.Rows _
  19.                         Order By r(columnIndex) _
  20.                         Descending
  21.                 For Each row In v
  22.                     Dim nr As DataRow = Me.NewRow
  23.                     nr.ItemArray = row.ItemArray.Clone
  24.                     result.Add(nr)
  25.                 Next
  26.         End Select
  27.         Me.Rows.Clear()
  28.         For Each row In result
  29.             Me.Rows.Add(row)
  30.         Next
  31.     End Sub
  32.  
  33.     Public Sub New(ByVal source As DataTable)
  34.         If Me.Columns.Count <> source.Columns.Count Then
  35.             For Each c As DataColumn In source.Columns
  36.                 Me.Columns.Add(c.Caption)
  37.             Next
  38.         End If
  39.         For Each r As DataRow In source.Rows
  40.             Dim nr As DataRow = Me.NewRow()
  41.             nr.ItemArray = r.ItemArray.Clone
  42.             Me.Rows.Add(nr)
  43.         Next
  44.     End Sub
  45.  
  46. End Class
  47.  
  48. Public Enum dDir
  49.     Ascending = 0
  50.     Descending = 1
  51. End Enum
  52.  
Adding this class to a project allows me to create a SortableDataTable, plus if I wish to apply this functionality to a table that already exists, I simply use the "New" constructor and pass in the table I want to sort like so...

Expand|Select|Wrap|Line Numbers
  1. Public Sub Button1_Click(sender as object, e as EventArgs)
  2.     Dim newTable As New SortableDataTable(oldTable)
  3.     newTable.Sort(0, dDir.Ascending);
  4. End Sub
  5.  
Unfortunately this way of going about things means you cannot cast a DataTable to an OrderedDataTable, however the reverse is possible. This means that if you wish to display your sorted data on a DataGridView for example, the DataSource property will also accept this type of class.

On a last note, I must admit there are probably easier ways to get this type of sorting implemented, however having an inherited class like this opens the possibility of advanced sorting.

Thanks for reading, and I hope it helps someone like it helped my colleague :)
Jul 2 '10 #1
0 3796

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Bobofrut | last post by:
Hi In my application I try to add one row from datagrid into datatable and I recive the following message: Exception Details: System.ArgumentException: This row already belongs to another...
2
by: Clinton Pierce | last post by:
I've filled a DataTable with columns that have custom type (a class that I'm using to keep track of other things, not just a value). When the .Select method goes to sort this column, how do I let...
2
by: a | last post by:
I get the error that "Argument"1": cannot convert from 'string' to 'System.Data.DataRow' at the foreach loop to add rows to the DataTable...any ideas how to fix this? Paul ...
3
by: Aleksey | last post by:
Hi, All! I have the following code: DataRow newDataRow; for (int i = 1; i <= count; i++) { newDataRow = table.NewRow();
6
by: Bart Schelkens | last post by:
Hi, I have another question. On my asp-page I put a label. I manually create a table and set that table in the text of the label. This way my table is displayed. My question is how can i...
0
by: cedoucette | last post by:
I just wrote code to support sortable columns in a datagrid. It seems to work fine; but, it doesn't look right. The problem is that I have a generic style for links and a different style for the...
2
by: Jon | last post by:
My application needs to present data generated at run time in a datagrid that can be sorted by clicking on columns, and where rows can be selected and events generated. Do I need to set up a...
3
by: TPhelps | last post by:
I have a sample of an unbound (autogeneratecolumns is true) sortable/pagable datagrid that works. I want to change one of the columns to a hyperlink. The examples I find use a bound column. I...
2
by: rusmo1 | last post by:
I have a GridvVew in which all of the columns are sortable. I want the first column to display the position of the row in the sorted order regardless of which column I've sorted or which direction...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

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.