C# DataGridView将时间显示为日期
我有一个CSV文件,其中有一列表示时间,时间的格式如下(在CSV文件中) 08:22:07 DataGridView将其转换为C# DataGridView将时间显示为日期,c#,c#-4.0,time,datagridview,datatable,C#,C# 4.0,Time,Datagridview,Datatable,我有一个CSV文件,其中有一列表示时间,时间的格式如下(在CSV文件中) 08:22:07 DataGridView将其转换为 12/30/1899 8:22 AM 有什么建议吗 我的代码看起来像 public static DataTable ParseCSV(string path, String pattern) { if (!File.Exists(path)) return null; string full =
12/30/1899 8:22 AM
有什么建议吗
我的代码看起来像
public static DataTable ParseCSV(string path, String pattern)
{
if (!File.Exists(path))
return null;
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";
string query = "SELECT [Pc-Tag], [User-Name], [Date], [Time] FROM " + file;// +" WHERE [User-Name] LIKE " + pattern;
DataTable dTable = new DataTable();
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
try
{
dAdapter.Fill(dTable);
}
catch (InvalidOperationException ioe)
{
Console.WriteLine(ioe.Message.ToString());
}
dAdapter.Dispose();
return dTable;
}
您可以将列配置为使用某种格式字符串,如
T
,这是长时间格式(hh:mm:ss)
使用包含时间值的列的DefaultCellStyle.Format
属性来执行此操作。您可以使用表单设计器(单击选择DataGridView
控件时显示的小箭头,然后选择“编辑列”,选择列,然后按下DefaultCellStyle
属性的“…”按钮),也可以在代码中执行此操作
只需确保手动添加列(在设计器中或在代码中),并将
AutoGenerateColumns
属性设置为false
您希望有多少行?
对于少数人(如果你有1500行,你会怎么做?@Thorsten-我会使用一个表达式,这要快得多。看看我更新的解决方案。
....
dAdapter.Dispose();
dtable.Columns.Add("Custom", typeof(string));
foreach(var row in dtable.Rows)
{
row["Custom"] = "17:15:30"; //here goes your logic to convert the Time Value
// example: row["Time"].ToString("T");
}
return dTable;
var expression = "SUBSTRING([Time], 11, IF(LEN([Time]) = 19, 8, 7))";
dtable.Columns.Add("Custom", typeof(string), expression);