1

I've 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 by:

            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'm binding a DataGridView to the DataTable accTable as follows:

            dataGridView1.DataSource = accTable;

How can I make the Date column sortable. By default, it is sorting alphabetically. Where can I set the type of the column to DateTime.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It worked! Thanks I didb't know abt how the type property could be assigned!
All I need to do now is work out how to get the underlying type from my nullable type.
Just a small point; you can do this all in one line: accTable.Columns.Add("Date",typeof(DateTime));
@BFree - true you can - I was just highlighting the Property
-1

For date data, we can use the following code:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.