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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10681378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:47:59  来源:igfitidea点击:

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

c#datetimegridviewformat

提问by Alex

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

我有一个 GridView,我想将它导出到 Word。我想将一列的格式更改为日期时间格式(“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# 更改格式,怎么做?

采纳答案by Eoin Campbell

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

如果要从 CodeBehind 更改 GridView 列的格式,请将 a 添加RowDataBound到您的网格视图。

Then in the GridView_RowDataBound(object sender, GridViewRowEventArgs e)method, you'll be able to access ewhich 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 RowDataBoundevent http://forums.asp.net/p/1589807/4025153.aspx

这是使用RowDataBound事件 http://forums.asp.net/p/1589807/4025153.aspx的示例

回答by Jeroen de Kort

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

回答by Nikhil Agrawal

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

回答by Waqar

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

OR

或者

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

回答by GodLesZ

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

Possible formats are shown in this MSDN article.

此 MSDN 文章中显示了可能的格式。

回答by V4Vendetta

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

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

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

我认为您需要将列转换为BoundField访问该属性。