C# DataGridView列的日期时间格式化

3
我有一个数据网格视图,它从数据库中获取数据,在其中有一些列包含日期和时间,格式为"MMddyyyy"和"hhmmss"。我想要做的是当数据网格视图加载时,将这种格式更改为其他格式,比如说日期使用"dd-MM-yy",时间使用"hh-mm-ss"。我想知道是否有人能够指导我怎么做。
我尝试使用gridview.columns[x].defaultcellstyle.format="dd-MM-yy",但是我没有成功。虽然上面的代码没有错误,但是在数据网格视图中什么也没有改变。
谢谢!
注意:我不能更改数据库中列的长度,语法没有问题。
2个回答

9
微软建议您拦截CellFormatting事件(其中DATED是您想要重新格式化的列):
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // If the column is the DATED column, check the
    // value.
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "DATED")
    {
        ShortFormDateFormat(e);
    }
}

private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
{
    if (formatting.Value != null)
    {
        try
        {
            DateTime theDate = DateTime.Parse(formatting.Value.ToString());
            String dateString = theDate.ToString("dd-MM-yy");    
            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;
        }
    }
}

为了缩短代码,您可以在列不可重新排序时检查列索引(if (e.ColumnIndex == 3) ...)。 - barbara.post

2

DataGridView格式化中的语法与DateTime有些不同,但您可以获得相同的结果。在我的示例中,我有一个时间列,默认显示HH:mm:ss,我想只显示小时和分钟:

 yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";

这种方法在DateTime格式化方面无法奏效。所以我使用了被接受的答案。有趣的是:如果你使用设计师编辑列,然后是单元格样式,再然后是格式,在这里只有一组有限的选择。例如,你不能将日期格式化为法国本地格式("dd/MM/yyyy"),提供的选项限于英语本地化。 - barbara.post

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接