首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置Datagridview列到时间的格式仅显示hh:mm:ss

设置Datagridview列到时间的格式仅显示hh:mm:ss
EN

Stack Overflow用户
提问于 2016-07-15 21:34:12
回答 2查看 3K关注 0票数 0

我正在用数据填充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。

下面是我的代码--有人能告诉我哪里做错了吗?

代码语言:javascript
复制
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";
EN

回答 2

Stack Overflow用户

发布于 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

票数 1
EN

Stack Overflow用户

发布于 2016-07-15 21:46:40

微软建议使用CellFormatting事件

代码语言:javascript
复制
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;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38397470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档