简体   繁体   English

如何从c#更改GridView中列的格式

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

I have a GridView and I want to export it to Word. 我有一个GridView,我想将其导出到Word。 I want to change the format of one column to datetime format ("dd.MM.yyyy") 我想将一列的格式更改为datetime格式(“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: 在* .aspx页面中,这非常简单,如下例所示:

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

I want change format from c#, how to do this? 我想从c#改变格式,怎么做?

If you want to alter the format of a column of a GridView from CodeBehind Add a RowDataBound to your grid view. 如果要从CodeBehind中更改GridView列的格式,请将RowDataBound添加到网格视图中。

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. 然后在GridView_RowDataBound(object sender, GridViewRowEventArgs e)方法中,您将能够访问e ,这将使您可以访问该行的各个单元格,您可以在其中指定格式化程序。

Here's an example of using the RowDataBound event http://forums.asp.net/p/1589807/4025153.aspx 以下是使用RowDataBound事件的示例http://forums.asp.net/p/1589807/4025153.aspx

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

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");
DateTime dt = DateTime.Now;
String formated = dt.ToString("dd.MM.yyyy");

OR 要么

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

Possible formats are shown in this MSDN article . 可能的格式显示在此MSDN文章中

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. 我认为您需要将列BoundFieldBoundField才能访问该属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM