How to sort a DataGridView column?

I created a DataTable as follows:

accTable = new DataTable(); accTable.Columns.Add(new DataColumn("Date")); accTable.Columns.Add(new DataColumn("Amt")); accTable.Columns.Add(new DataColumn("Item")); 

and filling it out:

  foreach (DataRow myDataRow in myDataSet.Tables[0].Rows) { DataRow accRow = accTable.NewRow(); //code skipped accRow["Date"] = date.ToString("d"); //tried without converting to string also accRow["Amt"] = int.Parse(cells[1].ToString()); accRow["Item"] = cells[2].ToString(); accTable.Rows.Add(accRow); } 

Then I bind the DataGridView to the DataTable attribute accTable as follows:

  dataGridView1.DataSource = accTable; 

How to sort a Date column. By default, it is sorted alphabetically. Where can I set the column type to DateTime.

+1
source share
2 answers

There is a DataType in the column. Have you tried setting the DateTime value?

 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 set the SortMode property for each column in the view:

 column.SortMode = DataGridViewColumnSortMode.Automatic; 

I had code that did all of this, but I converted it to use types with a null value (including DateTime fields), and it doesn't work as I expected. If I can return it again, I will update this answer.

+5
source

For date data, we can use the following code:

 dgv_transfer_from.Sort(dgv_transfer_from.Columns["Date_Out"], ListSortDirection.Ascending); 
-one
source

Source: https://habr.com/ru/post/1399339/


All Articles