3

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. 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 ...

Thanks

Note:I dont have the option to change the column length in the database as well..:-( there are no syntax problems

user1063108
  • 662
  • 1
  • 10
  • 24

2 Answers2

9

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;
        }
    }
}
OhBeWise
  • 5,350
  • 3
  • 32
  • 60
web_bod
  • 5,728
  • 1
  • 17
  • 25
2

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";
Lev Z
  • 742
  • 9
  • 17
  • This didn't work for DateTime formatting. So I go with accepted answer. What's interesting : if you use designer to edit columns, then cell style, then format, there is only a limited set of choice. For example you cannot format date to French locale format ("dd/MM/yyyy"), the proposed choices are bound to English locale. – barbara.post Jul 22 '14 at 14:56