开发者

Formatting dynamic GridView

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();
gvResul开发者_JAVA百科ts.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);


Here is an example:

<asp:BoundField DataField="DataFieldName" DataFormatString="{0:d}"></asp:BoundField>

And here is a link for reference:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx


When you add the column to the grid view you can setup the "DisplayFormat" to display currency.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜