phapha pha
phapha pha

Reputation: 329

How to format datetime to only specific DATE format in datatable

In my datagridview1, the DATE column show format "MM/dd/yyyy hh:mm:ss"

Then I use this code.

I use a function to fill a datagridview like this

public void load_table()
{
    DataTable ltdgv = getLoad_table(); 
    //the getLoad_table() function return a datatable type and store it to ltdgv

   foreach (DataRow dr in ltdgv.Rows)
   {
       dr["DATE"] = DateTime.Parse((dr["DATE"].ToString())).ToShortDateString();
   }

   dataGridView1.DataSource = ltdgv;           
}

but the DATE column still showing format MM/dd/yyyy [ex: 11/27/2016]

but I want to change it to dd/MM/yyyy or 27/11/2016

I tried to change it into =

dr["DATE"] = DateTime.Parse((dr["DATE"].ToString("dd/MM/yyyy"))).ToShortDateString();
// I fill a parameter to the .ToString()

But I now get a "syntax error".

So, how to fix this?

Upvotes: 4

Views: 36779

Answers (3)

kiran kumar k s
kiran kumar k s

Reputation: 1

In case of asp:BoundField

<asp:BoundField DataField="BirthDate" HeaderText="Birth Date" DataFormatString = "{0:dd/MM/yyyy}"  />

In case of asp:TemplateField

<asp:TemplateField HeaderText="Birth Date" ItemStyle-Width="120px" >
    <ItemTemplate>
        <asp:Label Text='<%# Eval("BirthDate", "{0:dd, MMM yyyy}") %>' runat="server" />
    </ItemTemplate>
</asp:TemplateField>

Upvotes: 0

Troy Mac1ure
Troy Mac1ure

Reputation: 647

Place the custom format in the output ToString(), not the input.

foreach (DataRow dr in ltdgv.Rows)
{
    dr["DATE"] = DateTime.Parse((dr["DATE"].ToString())).ToString("dd/MM/yyyy");
}

Upvotes: 4

Steve
Steve

Reputation: 216293

Do not try to change the 'format' of a datetime column in a datatable.
Simply a DateTime has no format by itself.

It is the tool that you use to display the date that has the task to present it in a human readable format, whatever this format is.

In other words. It is the DataGridView that must carry out this task.

You just need to set

dataGridView1.Columns[0].DefaultCellStyle.Format = "dd/MM/yyyy";

(Assuming that the grid column at index zero is your date column)

Upvotes: 9

Related Questions