Rahul Chowdhury
Rahul Chowdhury

Reputation: 1158

Showing date in MM/DD/YY format in a gridview column from .cs page/rowdatabound?

I am getting a date time field from database with timestamp.

My grid has an auto-generated column.

I am formatting it in my .cs page

dsWorkItems.Tables[0].Rows[count]["Date"] =
                    !string.IsNullOrEmpty(dsWorkItems.Tables[0].Rows[count]["Date"].ToString()) ?
                    ((DateTime)(dsWorkItems.Tables[0].Rows[count]["Date"])).ToShortDateString(): "";

In quick watch I am getting

((DateTime)(dsWorkItems.Tables[0].Rows[count]["Date"])).ToShortDateString() as 9/26/2013  

but in grid I am getting 9/26/2013 12:00:00 AM but I want to show in grid 9/26/13

And one more thing is it possible to show the full datetimestamp value from database in cell tooltip..

I have tried

 dsWorkItems.Tables[0].Columns["Date"].DefaultCellStyle.Format = "MM/dd/yy";

but DefaultCellStyle assembly missing i added System.Windows.Form but still not worked

Upvotes: 2

Views: 17070

Answers (1)

Amit
Amit

Reputation: 2565

Method 1: In aspx page.

The best thing to do in this case that I prefer to do is:

<asp:BoundField DataField="Modified" DataFormatString="{0:d}" 
   HeaderText="Modified On" HeaderStyle-BackColor="#D9EDF7"></asp:BoundField>

and set the AutoGenerateColumns="false" in the gridview.

Use BoundField for all the columns.

Method 2: In Codebehind have a row-databound event for your grid and perform the necessary formatting like this:

date1.ToString("d", DateTimeFormatInfo.InvariantInfo);

Cheers!!

Upvotes: 2

Related Questions