[英]How to sort a DataGridView Column?
I've created a DataTable as follows: 我创建了一个DataTable,如下所示:
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. 如何使Date列可排序。 By default, it is sorting alphabetically.
默认情况下,它按字母顺序排序。 Where can I set the type of the column to DateTime.
我在哪里可以将列的类型设置为DateTime。
The column has a DataType
. 该列具有
DataType
。 Have you tried setting that to DateTime
? 您是否尝试过将其设置为
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 DataTable
to a DataGridView
and then for each column on the view set the SortMode
property: 您将此
DataTable
绑定到DataGridView
,然后为视图上的每个列设置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. 我确实有一些代码完成了所有这些,但我将其转换为使用可空类型(包括DateTime字段),并且它不再像我预期的那样工作。 If I can get it working properly again I'll update this answer.
如果我能让它再次正常工作,我会更新这个答案。
对于日期数据,我们可以使用以下代码:
dgv_transfer_from.Sort(dgv_transfer_from.Columns["Date_Out"], ListSortDirection.Ascending);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.