格式化动态的GridView动态、GridView

由网友(小青蛙。)分享简介:我有一个GridView,其中列是动态的。 GridView控件被绑定到一个DataTable。 其中一列是一个日期时间列。我需要格式化列中显示,而不是01/01/2010 12:00:00。01/01/2010我无法将列更改为存储字符串,而不是一个DateTime。什么是做到这一点的最好方法是什么?< ASP:...

我有一个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 $将开往事件行数据创建,然后分析文本,并格式化你想要的方式。这只会工作,但如果你知道的日期将始终处于一个特定的列。

动态创建的gridview点击列头排序没反应

如果你想动列,但更多的控制是设置的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);

阅读全文

相关推荐

最新文章