简体   繁体   English

C#DataGridView列的日期时间格式

[英]C# DataGridView date time formatting of a column

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. 我有datagridview填充数据库中的数据,有些列我在其中有日期和时间“MMddyyyy”和“hhmmss”格式,我想要做的是当datagridview加载时,我想将此格式更改为其他格式比如,dd-MM-yy用于日期和时间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 ... 我无法通过gridview.columns [x] .defaultcellstyle.format =“dd-MM-yy”用上面的方法做到这一点我没有得到任何错误但在gridview上没有任何改变...

Thanks 谢谢

Note:I dont have the option to change the column length in the database as well..:-( there are no syntax problems 注意:我也没有选择更改数据库中的列长度.. :-(没有语法问题

Microsoft suggest you intercept the CellFormatting event (where DATED is the column you want to reformat): 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;
        }
    }
}

The sintax in DataGridView formating is a little different then in DateTime, but you can get the same result. DataGridView格式化中的sintax与DateTime略有不同,但您可以得到相同的结果。 In my example i have a Time collumn, that by default shows HH:mm:ss and I want to show only hours and minutes: 在我的例子中,我有一个Time collumn,默认显示HH:mm:ss,我想只显示小时和分钟:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM