简体   繁体   English

排序包含数字和字符串的DataGridView字符串列

[英]Sorting DataGridView string column containing numbers and strings

I have a bound DataGridView that displays file sizes: 我有一个绑定的DataGridView,它显示文件大小:

133 kb 133 kb
20 Mb 20兆
43.11 Mb 43.11 Mb
2.23 Gb 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? 如何在遵守数据单位的同时对它们进行数字排序?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM