列的C#DataGridView日期时间格式 [英] C# DataGridView date time formatting of a column

查看:1087
本文介绍了列的C#DataGridView日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有datagridview,它填充数据库中的数据,在其中有日期和时间的列中有 MMddyyyy和 hhmmss格式,我想做的是当datagridview加载时,我想将此格式更改为其他一些格式则是dd-MM-yy,用于日期和时间hh-mm-ss。我想知道是否有人可以指导我如何去做。
我没有通过gridview.columns [x] .defaultcellstyle.format = dd-MM-yy
做到这一点,我没有错误,但是gridview上没有任何变化。 ..

I have datagridview which fills data from database, there are columns where I have date and time in them "MMddyyyy" and "hhmmss" format, what I want to do is when the datagridview loads, I want to change this format to some other format say, dd-MM-yy for date and for time hh-mm-ss. I was wondering if some one can guide me how to do it. I have not been able to do this by gridview.columns[x].defaultcellstyle.format="dd-MM-yy" with the above I get no error but nothing is changed on the gridview ...

谢谢

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

Note:I dont have the option to change the column length in the database as well..:-( there are no syntax problems

推荐答案

Microsoft建议您拦截CellFormatting事件(其中DATED为要重新格式化的列):

Microsoft suggest you intercept the CellFormatting event (where DATED is the column you want to reformat):

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;
        }
    }
}

这篇关于列的C#DataGridView日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆