格式化动态的GridView [英] Formatting dynamic GridView

查看:142
本文介绍了格式化动态的GridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GridView,其中列是动态的。 GridView控件被绑定到一个DataTable。

其中一列是一个日期时间列。我需要格式化列中显示,而不是01/01/2010 12:00:00。

01/01/2010

我无法将列更改为存储字符串,而不是一个DateTime。

什么是做到这一点的最好方法是什么?

 < ASP:GridView控件ID =gvResults=服务器>
< / ASP:GridView控件>


CustomReportDataTable DT =新CustomReportDataTable();
dt.LoadData();
gvResults.DataSource = DT;
gvResults.DataBind();
 

解决方案

我假设你正在使用的网格与的AutoGenerateColumns,如果是这样的话,我不知道这样做,如果有一个正确的做法,但在这里是一个快速和肮脏的方法来改变正在输出的文本。

 保护无效grdTest_RowDataBound(对象发件人,GridViewRowEventArgs E)
    {
        如果(e.Row.DataItem!= NULL)
        {
            e.Row.Cells [1]。文= DateTime.Parse(e.Row.Cells [1]。文).ToShortDateString();
        }
    }
 

c您此$ C $将开往事件行数据创建,然后分析文本,并格式化你想要的方式。这只会工作,但如果你知道的日期将始终处于一个特定的列。

如果你想动列,但更多的控制是设置的AutoGenerateColumns为false,并动态地填充你想你绑定前的列网格视图的列,这样你可以使用的数据格式字符串另一种选择。这是一个多一点的工作,但你仍然可以控制你的专栏:

 绑定列COL1 =新的绑定列();
Col1.DataField =StringFieldName;

绑定列col2的=新的绑定列();
Col2.DataField =DateFieldName;
Col2.DataFormatString ={0:D};

grdTest.Columns.Add(COL1);
grdTest.Columns.Add(col2的);
 

I have a GridView, where the columns are dynamic. The GridView is being bound to a DataTable.

One of the columns is a DateTime column. I need to format that column to display "01/01/2010" instead of "01/01/2010 12:00:00 AM".

I can't change the column to store strings instead of a DateTime.

What's the best way to do this?

<asp:GridView ID="gvResults" runat="server">
</asp:GridView>


CustomReportDataTable dt = new CustomReportDataTable();
dt.LoadData();
gvResults.DataSource = dt;
gvResults.DataBind();

解决方案

I assume you are using the grid with the AutoGenerateColumns if this is the case, I am not sure the correct way to do it if there is one, but here is a quick and dirty way to change the text that is being output.

 protected void grdTest_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            e.Row.Cells[1].Text = DateTime.Parse(e.Row.Cells[1].Text).ToShortDateString();
        }
    }

This code you will create a on row data bound event, and then parse the text, and format it the way you want. This will only work though if you know that the date will always be in a specific column.

Another option if you want dynamic columns but more control would be to set AutoGenerateColumns to false and dynamically populate the columns of the grid view with the columns you want before you bind it, that way you can use the data format string. This is a little bit more work, but you still can control your columns:

BoundField Col1 = new BoundField();
Col1.DataField = "StringFieldName";

BoundField Col2 = new BoundField();
Col2.DataField = "DateFieldName";
Col2.DataFormatString = "{0:d}";

grdTest.Columns.Add(Col1);
grdTest.Columns.Add(Col2);

这篇关于格式化动态的GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆