C# DataGridView date time formatting of a column

前端 未结 2 612
长情又很酷
长情又很酷 2021-01-20 19:16

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 da

相关标签:
2条回答
  • 2021-01-20 19:36

    The sintax in DataGridView formating is a little different then in DateTime, but you can get the same result. In my example i have a Time collumn, that by default shows HH:mm:ss and I want to show only hours and minutes:

     yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";
    
    0 讨论(0)
  • 2021-01-20 19:43

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题