vb.net 如何按日期时间类型的列值对 datagridview 进行排序。?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15310541/
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
How to Sort datagridview by column values which are of datetime type.?
提问by Anupam PB
I have a problem while sorting datagridview by column2 (name of the column i used )
我在按 column2(我使用的列的名称)对 datagridview 进行排序时遇到问题
i used datetime type values in the column and now i want to sort the grid ( named as conv_msg_grid) by using following command
我在列中使用了日期时间类型值,现在我想使用以下命令对网格(命名为 conv_msg_grid)进行排序
conv_msg_grid.Sort(Column2, System.ComponentModel.ListSortDirection.Ascending)
but it is giving an error " Object must be of type String."
但它给出了一个错误“对象必须是字符串类型。”
what is wrong in it???
有什么问题吗???
please help me out.....
请帮帮我.....
回答by WozzeC
Seems like you have inconsistent datatypes in your table. Your first item(s) are of type string, but some of them are of type date. So when you try to sort and you hit something which isn't a string this error occurs.
似乎您的表中有不一致的数据类型。您的第一项是字符串类型,但其中一些是日期类型。因此,当您尝试排序并遇到不是字符串的内容时,会发生此错误。
To solve it you have two options.
要解决它,您有两种选择。
Before sorting turn everything into datetime (or string) values. (This is the better choice if the user is allowed to add dates)
When inserting data into the DatagridView you make sure that all the values are of DateTime (or string). (This is the better choice if the user can't type in dates)
在排序之前将所有内容转换为日期时间(或字符串)值。(如果允许用户添加日期,这是更好的选择)
将数据插入 DatagridView 时,请确保所有值都是 DateTime(或字符串)。(如果用户不能输入日期,这是更好的选择)
To do the (or string) option simply remove convert.ToDateTime and do ToString on value.
要执行(或字符串)选项,只需删除 convert.ToDateTime 并对值执行 ToString 。
Dim Column2 As DataGridViewColumn = DataGridView1.Columns(0)
For Each r As DataGridViewRow In DataGridView1.Rows
r.Cells(Column2.Index).Value = Convert.ToDateTime(r.Cells(Column2.Index).Value)
Next
回答by Kalunche Che
conv_msg_grid.Sort(conv_msg_grid.columns(2), System.ComponentModel.ListSortDirection.Ascending)
conv_msg_grid.Sort(conv_msg_grid.columns(2), System.ComponentModel.ListSortDirection.Ascending)
Kalunche
卡伦切

