C# DataGridView 列的日期时间格式

标签 c# .net winforms

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

谢谢

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

最佳答案

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

关于C# DataGridView 列的日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10644788/

相关文章:

.net - 如何让 System.Web.Optimization 包与 IIS 虚拟目录中的自定义文件夹一起使用?

c# - 更改 WCF 引用 URL .Net Core

c# - XML 对象反序列化到接口(interface)

c# - 如何使用 Graphics.DrawString 绘制双倍高度文本?

c# - 删除绑定(bind)到控件的图像

java - .NET 上没有的 Java/Ruby 等很酷的框架有哪些?

c# - 绘制 8bpp 位图时如何使调色板中的颜色透明

c# - 使用 C# 和 WinForms 在自己的进程中的选项卡

c# - 哪种调用 Form.ShowDialog() 的方法更好?

c# - Axis2 MTOM Web 服务和使用它的 .NET 客户端