How to change the format of a column in GridView from c#

耗尽温柔 提交于 2019-12-11 10:29:04

问题


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?


回答1:


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




回答2:


String.Format("{0:dd.MM.yyyy}", myDateTimeInstance);



回答3:


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");



回答4:


DateTime dt = DateTime.Now;
String formated = dt.ToString("dd.MM.yyyy");

OR

String formated = String.Format("{0:dd.MM.yyyy}", dt );



回答5:


DateTime dt = DateTime.Now;
string formated = dt.ToString("dd.MM.yyyy");

Possible formats are shown in this MSDN article.




回答6:


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.



来源:https://stackoverflow.com/questions/10681378/how-to-change-the-format-of-a-column-in-gridview-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!