tags:

views:

290

answers:

5

I would like to change the way a DateTime object is displayed in a DataGridView. Specifically, I would like to have seconds displayed with the time.

c# .net 2.0

+1  A: 

One way is to handle the CellFormattingEvent event and then you can display the data how you want.

Matt Warren
thanks for the link
fishhead
+1  A: 

You can try to edit RowDefaultCellStyle->format in design and choose acceptable format, or use this:

DataGridViewCellStyle customStyle = new DataGridViewCellStyle();
customStyle.Format = "T";
customStyle.NullValue = null;
customGridView.RowsDefaultCellStyle = customStyle;
Andrew
+1  A: 

Override the OnRowDataBound event and read a bit more about cultures and formatting in .Net

protected override void OnRowDataBound(GridViewRowEventArgs e)
{

    base.OnRowDataBound(e);


    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      for (int i = 0; i < e.Row.Cells.Count; i++)
        {

                  TableCell cell = e.Row.Cells[i];
                  cell.Text = DateTime.Parse ( cell.Text, culture ); 
         }  
    }
    }
YordanGeorgiev
+10  A: 
dataGridView1.Columns[0].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";

For specific formatting, check out these links:

Gabriel McAdams
This is the correct way of formatting a DateTime if you don't need any special cases for displaying something else entirely.
Justin Drury
@Justin: I'm not sure what you're saying. Can you give me more information?
Gabriel McAdams
Our company has the case where if DateTime is a certain value, it needs to display as an empty string. To do that you would use the CellFormatting event on the DataGridView
Justin Drury
+6  A: 

Here's examples of 3 different ways:

  • format string on the cell template
  • cell-formatting event
  • custom type converter

Any use?

using System;
using System.ComponentModel;
using System.Windows.Forms;
public class MyData
{
    public DateTime A { get; set; }
    public DateTime B { get; set; }
    public DateTime C { get; set; }
    [TypeConverter(typeof(CustomDateTimeConverter))]
    public DateTime D { get; set; }
}
class CustomDateTimeConverter : DateTimeConverter
{
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            return ((DateTime)value).ToString("dd-MM-yyyy HH:mm:ss");
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}
static class Program {
    [STAThread]
    static void Main()
    {
        DateTime when = DateTime.Now;
        var data = new BindingList<MyData>
        {
            new MyData { A = when, B = when, C = when }
        };
        using (var form = new Form())
        using (var grid = new DataGridView {
            AutoGenerateColumns = false,
            DataSource = data, Dock = DockStyle.Fill })
        {
            form.Controls.Add(grid);
            grid.Columns.Add(
                new DataGridViewTextBoxColumn {
                    HeaderText = "Vanilla",
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
                    DataPropertyName = "A",
                });
            grid.Columns.Add(
                new DataGridViewTextBoxColumn {
                    HeaderText = "Format",
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
                    DataPropertyName = "B",
                    DefaultCellStyle = { Format = "dd/MM/yyyy HH:mm:ss" }
                });
            grid.Columns.Add(
                new DataGridViewTextBoxColumn {
                    HeaderText = "CellFormatting",
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
                    DataPropertyName = "C",
                });
            grid.CellFormatting += (sender, args) =>
            {
                if (args.Value != null && args.ColumnIndex == 2
                    && args.DesiredType == typeof(string))
                {
                    args.Value = ((DateTime)args.Value).ToString("dd MM yyyy HH:mm:ss");
                }
            };
            grid.Columns.Add(
                new DataGridViewTextBoxColumn {
                    HeaderText = "TypeConverter",
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
                    DataPropertyName = "D",
                });
            Application.Run(form);
        }
    }

}
Marc Gravell
+1 for the most complete answer, pick the simplest solution that fits your needs.
Johannes Rudolph
This answer made me tag the question as favorite ۞
awe
thanks for this complete answer
fishhead