【问题标题】:C# DataGridView date time formatting of a column列的 C# DataGridView 日期时间格式
【发布时间】:2016-12-16 23:29:10
【问题描述】:

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

谢谢

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

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

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

    【讨论】:

    • 为了缩短代码,您可以在列不可重新排序时检查列索引(如果 (e.ColumnIndex == 3)...)
    【解决方案2】:

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

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

    【讨论】:

    • 这不适用于 DateTime 格式。所以我接受了接受的答案。有趣的是:如果您使用设计器编辑列,然后是单元格样式,然后是格式,则只有有限的选择。例如,您不能将日期格式化为法语语言环境格式(“dd/MM/yyyy”),建议的选择绑定到英语语言环境。
    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多