0

我有一个显示文件大小的绑定 DataGridView:

133 kb
20 Mb
43.11 Mb
2.23 Gb

ETC

我通常会确保数据源(此处为数据表)中的列类型是十进制的,但该值包含阻止这种情况的大小指定。如何在遵守数据单元的同时对它们进行数字排序?

4

1 回答 1

1

这就是我现在所拥有的。

<!-- 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
于 2012-09-27T12:58:50.990 回答