简体   繁体   中英

How to sort DataGridView Column by date in VB visual studio 2012?

In my DGV, I have date list in the column (1):

11-Sep-2014
11-May-2011
11-Jan-2014
11-Mar-2014
12-Sep-2010

how to get descending result like this:

11-Sep-2014
11-Mar-2014
11-Jan-2014
11-May-2011  
12-Sep-2010

The Column(1) is not DateTime type but SortText type, I must set string like that. Could it sorted?

I have tried using code:

DGV.Columns(1).SortMode = DGV.Sort(DGV.Columns(1), System.ComponentModel.ListSortDirection.Descending)

but it's useless, it don't sort by date :(

this is my DGV:在此处输入图片说明

Okeh, this is my DGV code in brief:

Imports System.Data.OleDb

Public Class LapTransaksiSimpanan

Public Sub Koneksi()
    str = "provider=microsoft.jet.oledb.4.0;data source=dbkoperasi.mdb"
    Conn = New OleDbConnection(str)
    If Conn.State = ConnectionState.Closed Then
        Conn.Open()
    End If
End Sub

Sub TampilGrid()
    da = New OleDbDataAdapter("select * from LapTransaksiSimpanan", Conn)
    ds = New DataSet
    da.Fill(ds, "LapTransaksiSimpanan")
    DGV.DataSource = ds.Tables("LapTransaksiSimpanan")

    'on the below I wanna to sort the column, my code below is useless :(
    DGV.Sort(DGV.Columns(1), System.ComponentModel.ListSortDirection.Descending)

    DGV.Columns("ID_Simpanan").Width = 120
    DGV.Columns("NAK").Width = 37
    DGV.Columns("Tanggal").Width = 75
    DGV.Columns("Jumlah").Width = 110
End Sub

Private Sub Setoran_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Call Koneksi()
    Call TampilGrid()
End Sub

End Class

There's a difference between storing and displaying data.

You need to change you database table schema. The Tanggal column should be of type date or datetime . When you've fixed this, it's trivial to display dates using a custom format:

Me.DGV.Columns("Tanggal").DefaultCellStyle.Format = "dd-MMM-yyyy"

If you for some reason cannot change the schema, then you need to create a custom comparer by implementing IComparer . There's an example at the bottom ofthis MSDN page .

    Dim tnd As Date
    For Me.i = 0 To X1.RowCount - 2
        tnd = X1.Item(1, i).Value
        X1.Item(6, i).Value = tnd.ToOADate.ToString
    Next

X1 is DataGridView Column 1 would have your date ex 5/4/1987 Column 6 would be calculated as MS date number in integer and must be converted to string. Make sure X1 grid is Sort enabled Now simply click on Column 6 header to sort. Hope that works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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