How to Format Datetime Columns in Datagridview

How to format DateTime columns in DataGridView?

If it is a windows form Datagrid, you could use the below code to format the datetime for a column

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";

EDIT :

Apart from this, if you need the datetime in AM/PM format, you could use the below code

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";

Format date in DataGridView column in custom format

This seems to work:

Imports System.Globalization

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim table As New DataTable

With table.Columns
.Add("ID", GetType(Integer)).AutoIncrement = True
.Add("Name", GetType(String))
.Add("Date", GetType(Date)).AllowDBNull = True
End With

With table.Rows
.Add(1, "Peter", #1/1/2000#)
.Add(2, "Paul", #6/19/1969#)
.Add(3, "Peter", Date.Today)
End With

DataGridView1.DataSource = table

'Use the display format by default.
DataGridView1.Columns(2).DefaultCellStyle.Format = "dd.MM.yyyy"
End Sub

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If DataGridView1.CurrentCellAddress.X = 2 Then
'Display the date in the editing format.
Dim cellValue = DataGridView1.CurrentCell.Value
Dim text = If(cellValue Is DBNull.Value, String.Empty, CDate(cellValue).ToString("ddMMyy"))

e.Control.Text = text
End If
End Sub

Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
If e.ColumnIndex = 2 AndAlso
DataGridView1.EditingControl IsNot Nothing AndAlso
Not e.FormattedValue.Equals(String.Empty) Then
Dim value As Date

'Validate the input using the editing format and the display format.
e.Cancel = Not Date.TryParseExact(CStr(e.FormattedValue),
{"ddMMyy", "dd.MM.yyyy"},
Nothing,
DateTimeStyles.None,
value)

If Not e.Cancel Then
'Ensure data is displayed using the display format.
DataGridView1.EditingControl.Text = value.ToString("dd.MM.yyyy")
End If
End If
End Sub

End Class

When an editing session begins, the text in the editing control is explicitly formatted as "ddMMyy" and, if the input passes validation, the text is converted back to "dd.MM.yyyy" format so that the grid will automatically parse it back to a Date.

Formatting a datagridview column to display formatted datetime instead of serial datetime

Use CellFormating event:

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == Datecolumn.Index && e.Value !=null)
{
e.Value = DateTime.ParseExact(Convert.ToInt64(e.Value).ToString(), "yyyyMMddHHmmss", null).ToString("dd/MM/yyyy hh:mm:ss tt");
e.FormattingApplied = true;
}
}

Formatting double to DateTime is an example. I do not know if this is your format of date. You can also modify condition e.ColumnIndex == Datecolumn.Index so it would be good for all of your columns (e.g. check if index in in some kind of array/list of valid indexes)

Format DateTime in DataGridView

You could add the Column as string:

_dtdate.Columns.Add(new DataColumn("Maintenance Date", typeof(String)));

and then format the date when adding a new row:

_dtdate.Rows.Add(startdate.Date.ToString("dd/MM/yyyy"), taskID, machine, note, period);

C# DataGridView date time formatting of a column

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

Format date-string from datagridview to dd/MM/yyyy in C#

You should convert to a datetime the property Value of your DataGridViewRow. This is typed as an object so you need a conversion. At that point you can use the overload of ToString available for the DateTime type that accepts the output format required.

For clarity I put the code in separate lines.

 DateTime dt = Convert.ToDateTime(dataGridView1.Rows[i].Cells["Date"].Value);
string toOutput = dt.ToString("dd/MM/yyyy");
e.Graphics.DrawString(toOuput, new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height);

My datagridview binded with MS Access Database displays wrong time format

you can try to set the DefaultStyle property like this

dataGridView1.Columns["YourColumn"].DefaultCellStyle.Format = "HH:mm:ss";

Or set it in the designer, whatever you like most.

In your database your Time column seems to have only a time value, but it has not. It uses the lowest possible date value, which is 30/12/1899 for an Access Database.

This happens when you only feed that column with a time, and no date. Acces (and other databases also) will simply use their lowest possible date value to fill up the missing date value.

The DataGridView therefor has no choice but to also show the date along with its time.

The property above will simply instruct the DataGridView to not show the date part, only the time part.

If you need to display the time in code in C#, you could use this

YourDateTimeVariable.ToString("T");

But, since you are storing both date and time in datetime columns, why do you store them seperate ?

You could just store them in one column, and show/use only the part you need.

EDIT

to respond to the code you posted in the comments (please add this code in your question, not in the comments)

change this

invoicesDatagridview.Rows[i].Cells[1].Value.ToString())

into this

((datetime)invoicesDatagridview.Rows[i].Cells[1].Value).ToString("T"))

in case this column can by null you will need some extra checks to avoid cast errors.

Also, the format in the GridCell willl never be used in a ToString(), you are doing the ToString() on the value, not on the display text.

Try the code above to fix this

EDIT

To respond to your comment below:

Printing code is not the point. I just want to know that how can datagridview cell value and print value be of different format –
karan ugale

By setting the DefaultCellStyle you tell the DataGridView what format to use to display the value. When you print this value with your own code using ToString(), how on earth should this ToString() know of the DefaultCellStyle setting ? The print code with ToString() has absolutly no connection with the DataGridView, you just pass it the value nothing more.

Look at this example

invoicesDatagridview.Rows[i].Cells[1].Value.ToString())

this can be written like this

var someValue = invoicesDatagridview.Rows[i].Cells[1].Value;
someValue.ToString();

now tell me, how should someValue.ToString() know of any format ?



Related Topics



Leave a reply



Submit