我正在用数据填充datagridview,其中一列应该显示为time,即hh:mm:ss。
从Access数据库中提取数据并成功填充到datagridview中。我希望显示为时间的列在access数据库中填充为"Number“。正如您将看到的,我在select查询中使用/86400将其转换为秒。
当我尝试使用DefaultCellStyle.Format = "hh:mm:ss tt“转换列时,整个数据列在每个单元格中都被替换为"hh:mm:ss tt",即不再有数字,每个单元格中只有hh:mm:ss tt。
下面是我的代码--有人能告诉我哪里做错了吗?
string strProvider =
"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = P:\\JC_StockFile\\Mitel\\Mitel.accdb";
string strSql =
"SELECT [MidnightStartDate], [Agent Name], [LoginTime], [LogoutTime], [ShiftDuration]/86400 as ShiftDuration " +
"FROM login_data " +
"WHERE [MidnightStartDate] > @LeDate";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@LeDate", DateTime.Today.AddDays(-3) );
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;
dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "hh:mm:ss tt";发布于 2016-07-15 21:40:48
我相信这个属性的工作原理和其他字符串格式一样。编辑:我认为实际上你只是有一个大写的问题:
试试这个:
dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "HH:mm:ss";
参考:https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
发布于 2016-07-15 21:46:40
微软建议使用CellFormatting事件
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// If the column is the ShiftDuration column, check the
// value.
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ShiftDuration")
{
ShortFormDateFormat(e);
}
}
private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
{
if (formatting.Value != null)
{
try
{
DateTime theDate = DateTime.Parse(formatting.Value.ToString());
String dateString = theDate.toString("hh:mm:ss tt");
formatting.Value = dateString;
formatting.FormattingApplied = true;
}
catch (FormatException)
{
// Set to false in case there are other handlers interested trying to
// format this DataGridViewCellFormattingEventArgs instance.
formatting.FormattingApplied = false;
}
}
}https://stackoverflow.com/questions/38397470
复制相似问题