C# 如何对 DataGridView 列进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/857115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:24:55  来源:igfitidea点击:

How to sort a DataGridView Column?

c#

提问by Milen

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:

然后我将 DataGridView 绑定到 DataTable accTable,如下所示:

            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.

如何使日期列可排序。默认情况下,它按字母顺序排序。在哪里可以将列的类型设置为 DateTime。

采纳答案by ChrisF

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

该列有一个DataType. 您是否尝试将其设置为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):

当然,您可以在一行上执行此操作(感谢 BFree):

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

You bind this DataTableto a DataGridViewand then for each column on the view set the SortModeproperty:

您将其绑定DataTable到 aDataGridView然后为视图上的每一列设置SortMode属性:

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.

我确实有一些代码可以完成所有这些,但是我将其转换为使用可为空类型(包括 DateTime 字段),并且它不再像我预期的那样工作。如果我能让它再次正常工作,我会更新这个答案。

回答by Ahmad Hassan

For date data, we can use the following code:

对于日期数据,我们可以使用以下代码:

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