1

I have a GridView and I want to export it to Word. I want to change the format of one column to datetime format ("dd.MM.yyyy")

var grid = new GridView { DataSource = dt};
grid.DataBind();

In *.aspx page this is very easy, it looks like in the example below:

<asp:boundfield datafield="My_Date_Column"
                dataformatstring="{0:dd.MM.yyyy}"
                htmlencode="false" />

I want change format from c#, how to do this?

ChrisF
  • 131,190
  • 30
  • 250
  • 321
Alex
  • 7,986
  • 27
  • 93
  • 150

6 Answers6

3

If you want to alter the format of a column of a GridView from CodeBehind Add a RowDataBound to your grid view.

Then in the GridView_RowDataBound(object sender, GridViewRowEventArgs e) method, you'll be able to access e which will provide you with access to the individual cells of that row where you can specify a formatter.

Here's an example of using the RowDataBound event http://forums.asp.net/p/1589807/4025153.aspx

Eoin Campbell
  • 42,194
  • 17
  • 98
  • 153
1
String.Format("{0:dd.MM.yyyy}", myDateTimeInstance);
0

I think the format of column is based in system current date time format.

But when converting to string you can do so

String str = dt[RowNumber][ColumnName].ToString("dd.MM.yyyy");
Nikhil Agrawal
  • 44,717
  • 22
  • 115
  • 201
0
DateTime dt = DateTime.Now;
String formated = dt.ToString("dd.MM.yyyy");

OR

String formated = String.Format("{0:dd.MM.yyyy}", dt );
Waqar
  • 2,391
  • 16
  • 15
0
DateTime dt = DateTime.Now;
string formated = dt.ToString("dd.MM.yyyy");

Possible formats are shown in this MSDN article.

GodLesZ
  • 900
  • 5
  • 6
0

In case you want to format the entire column then it would be better if you can set the property for your concerned column

gridview1.Columns[columnIndex].DataFormatString ="{0:dd.MM.yyyy}";

I think you will need to cast the column as BoundField to access the property.

V4Vendetta
  • 35,718
  • 7
  • 75
  • 81
  • do you mind to check my thread? http://stackoverflow.com/questions/39157400/how-to-set-formatting-date-time-on-repositoryitem-combobox –  Aug 26 '16 at 02:59