How to sort a DataGridView Column?

后端 未结 2 546
面向向阳花
面向向阳花 2021-01-16 05:29

I\'ve created a DataTable as follows:

        accTable = new DataTable();
        accTable.Columns.Add(new DataColumn(\"Date\"));
        accTable.Columns.Ad         


        
相关标签:
2条回答
  • 2021-01-16 06:09

    The column has a DataType. Have you tried setting that to DateTime?

    var accTable = new DataTable();
    
    var columnSpec = new DataColumn("Date");
    columnSpec.DataType = typeof(DateTime);
    accTable.Columns.Add(columnSpec);
    

    Of course you can do this on one line (thanks to BFree):

    accTable.Columns.Add("Date",typeof(DateTime));
    

    You bind this DataTable to a DataGridView and then for each column on the view set the SortMode property:

    column.SortMode = DataGridViewColumnSortMode.Automatic;
    

    I did have some code that did all this, but I converted it to use nullable types (including the DateTime fields) and it's not working as I expected any more. If I can get it working properly again I'll update this answer.

    0 讨论(0)
  • 2021-01-16 06:17

    For date data, we can use the following code:

    dgv_transfer_from.Sort(dgv_transfer_from.Columns["Date_Out"], ListSortDirection.Ascending);
    
    0 讨论(0)
提交回复
热议问题