Sort dirInfo.GetFiles("*.*") collection in DataGrid

  • Thread starter Thread starter Hrvoje Vrbanc
  • Start date Start date
H

Hrvoje Vrbanc

Hello all!

I have a small problem: I have an ASP.NET page that displays content of a
folder in a DataGrid (more precisely, it displays Name, Lenth and
CreationDate of the files).
Default sort order is by file Name. Howwever, I would like to sort the
collection by the CreationDate.
How to do it?

I use the following code:

Dim dirInfo As New DirectoryInfo(directoryPath)
Dim FileNo As Integer = dirInfo.GetFiles("*.*").Length
If FileNo > 0 Then
dgFiles.DataSource = dirInfo.GetFiles("*.*")
dgFiles.DataBind()
Else
dgFiles.Visible = False
End If

Thank you very much in advance!
Hrvoje
 
You can a write a wrapper class that uses DirectoryInfo and implements
IComparable...
 
Use arraylist and IComparer. Code below

Private Class FileInfoCreationComparer
Implements IComparer

Public Function Compare(ByVal x As Object, ByVal y As Object)
As Integer Implements System.Collections.IComparer.Compare
Dim xFile As FileInfo = CType(x, FileInfo)
Dim yFile As FileInfo = CType(y, FileInfo)
Dim time As TimeSpan =
xFile.CreationTime.Subtract(yFile.CreationTime)
Return time.Minutes
End Function
End Class

''''' Changed data binding implementation. Add the files into a array
list and sort.

Dim dirInfo As New DirectoryInfo(directoryPath)
Dim FileNo As Integer = dirInfo.GetFiles("*.*").Length
If FileNo > 0 Then
''Changed Code'''
Dim files() as FileInfo = dirInfo.GetFiles() ''No need for filter
"*.*" if you are selecting everything
Dim list as new ArrayList (files) ''Add the files array to an
array list
list.Sort (new FileInfoCreationComparer())
dgFiles.DataSource = list ''Bind to the array list
dgFiles.DataBind()
Else
dgFiles.Visible = False
End If


NuTcAsE
 
Back
Top