madlan
madlan

Reputation: 1397

Sorting DataGridView string column containing numbers and strings

I have a bound DataGridView that displays file sizes:

133 kb
20 Mb
43.11 Mb
2.23 Gb

etc

I would usually ensure the column type was decimal in the DataSource (Datatable here) but the value contains size designations preventing this. How can I sort them both numerically while abiding by the data units?

Upvotes: 0

Views: 1772

Answers (1)

cardano dev 12
cardano dev 12

Reputation: 81

This is what I have now.

<!-- language: lang-vb-->
     Dim d As New DataTable()

    Dim c As New DataColumn("Size")
    c.DataType = GetType(Integer)

    Dim c2 As New DataColumn("SizeInUnits")
    c2.DataType = GetType(String)

    d.Columns.Add(c)
    d.Columns.Add(c2)

    Dim strFileSize As String = ""
    Dim di As New IO.DirectoryInfo("C:\temp")
    Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")


    For Each fi As IO.FileInfo In aryFi
        Dim r As DataRow = d.NewRow()
        r(0) = fi.Length
        r(1) = GetSizeInUnits(fi.Length)
        d.Rows.Add(r)
    Next

    d.DefaultView.Sort = "Size ASC"
    DataGridView1.DataSource = d
    DataGridView1.Columns(0).Visible = False

    'New Code Here, Don't Auto Sort. We will sort the data ourselves in event
    'DataGridView1_ColumnHeaderMouseClick. You will have to do some additional work
    'to determin the sort direction. i.e. If Current Sort Order is ASC, the sort DESC 
    'and vice versa
    DataGridView1.Columns(1).SortMode = DataGridViewColumnSortMode.Programmatic

     Private Sub DataGridView1_ColumnHeaderMouseClick(ByVal sender As System.Object, ByVal e As        System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick
            DataGridView1.Sort(DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Descending)
     End Sub

    Private Function GetSizeInUnits(ByVal size As Double) As String
    Dim sizeKB As String = "KB"
    Dim sizeMB As String = "MB"
    Dim sizeGB As String = "GB"

    If (size < 1000000) Then
        Return size / 1000 & sizeKB
    End If

    If (size > 1000000 AndAlso size < 1000000000) Then
        Return size / 1000000 & sizeMB
    End If

    If (size > 1000000000) Then
        Return size / 1000000000 & sizeGB
    End If

    End Function

Upvotes: 1

Related Questions