vb.net 如何将 datagridview 列设置为日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24437920/
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 set a datagridview column to date format
提问by John
I have created a DataGridView and I add columns to it like this:
我创建了一个 DataGridView 并向其添加列,如下所示:
Dim col_1 = New DataGridViewTextBoxColumn
col_1.Name = "Date"
col_1.DefaultCellStyle.Format = "MM/dd/yyyy"
data_grid.Columns.Add(col_1)
then I add data to the column like this:
然后我像这样将数据添加到列中:
data_grid.Item(1,1).Value = temp_date
The grid is filled with the correct data and everything works, however...when I click on the column headers, the column that shows the dates does not sort correctly (it sorts alphabetically) and I know this is because I set it up as "DataGridViewTextBoxColumn", but there is no option for a date type column. So how to I set it up as a date column so it sorts based on the date when the header is clicked?
网格填充了正确的数据并且一切正常,但是...当我单击列标题时,显示日期的列排序不正确(按字母顺序排序),我知道这是因为我将其设置为“DataGridViewTextBoxColumn”,但没有日期类型列的选项。那么如何将其设置为日期列,以便根据单击标题时的日期进行排序?
Thanks.
谢谢。
回答by Andy G
You should also set the ValueTypeof the column:
您还应该设置ValueType列的:
DataGridView1.Columns(0).ValueType = GetType(Date)
Then convert date_tempto a Date-value before assigning this to the cell's Value.
然后date_temp在将其分配给单元格的值之前转换为日期值。
Using CDatecould be your first attempt:
使用CDate可能是您的第一次尝试:
data_grid.Item(1,1).Value = CDate(temp_date)
otherwise, investigate Parse, TryParseor Convert, to obtain the date-value.
否则,调查Parse,TryParse或者Convert,以获取日期值。

