3

我有从数据库中填充数据的datagridview,有些列中我有日期和时间“MMddyyyy”和“hhmmss”格式,我想要做的是当datagridview加载时,我想将此格式更改为其他格式比如说,dd-MM-yy 代表日期和时间 hh-mm-ss。我想知道是否有人可以指导我如何做到这一点。我无法通过 gridview.columns[x].defaultcellstyle.format="dd-MM-yy" 执行此操作,但我没有收到任何错误,但 gridview 上没有任何更改...

谢谢

注意:我也没有选择更改数据库中的列长度..:-( 没有语法问题

4

2 回答 2

9

Microsoft 建议您拦截 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;
        }
    }
}
于 2012-05-17T23:28:40.063 回答
2

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

 yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";
于 2014-03-27T14:53:59.927 回答