C # DataGridView formatting date in column

I have a datagridview that fills the data from the database, there are columns in which I have the date and time in the format "MMddyyyy" and "hhmmss", what I want to do, when the datagridview is loaded, I want to change this format to whatever then another format says: dd-MM-yy for date and time hh-mm-ss. I was wondering if anyone could help me how to do this. I could not do this using gridview.columns [x] .defaultcellstyle.format = "dd-MM-yy" with the above, I do not get errors, but nothing changes in gridview ...

thank

Note. I also have no way to change the length of a column in the database .. :-( no syntax problems

+3
source share
2 answers

Microsoft will offer you to 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;
        }
    }
}
+8
source

The syntax in generating a DataGridView is slightly different from DateTime, but you can get the same result. In my example, I have a time column that shows HH: mm: ss by default, and I want to show only hours and minutes:

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

All Articles