简体   繁体   中英

Format DataTable Column for Percent

I have a Gridview

<asp:GridView runat="server" ID="gvTrades" GridLines="None" CellPadding="0" CellSpacing="0" AutoGenerateColumns="true"></asp:GridView>

And I am trying to format the first column into a percentage including the '%'. However, I can't access the column by name. I want to do this from the code-behind and not use a boundfield in the aspx page.

DataTable dt = SOME METHOD TO FILL UP THE DATATABLE;
gvTrades.DataSource = dt;
gvTrades.DataBind();

This is kind of what I'm trying to do:

gvTrades.Columns["MyColumnName"].Text = {0:P};

If you are fine with hardcoding the column index, you could just simply do this in the RowDataBound event:

<asp:GridView runat="server" 
    ID="gvTrades" 
    GridLines="None" 
    CellPadding="0" 
    CellSpacing="0" 
    AutoGenerateColumns="true"
    OnRowDataBound="gvTrades_RowDataBound">
</asp:GridView> 
protected void gvTrades_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[0].Text = String.Format("{0}%", e.Row.Cells[0].Text);
    }
}

If not, you can loop each cell of the HeaderRow looking for a specific column name. Once you find the correct column, you have the index you need. This would be better done in the GridView DataBound method so that you are not having to loop all the header cells for every single row.

<asp:GridView runat="server" 
    ID="gvTrades" 
    GridLines="None" 
    CellPadding="0" 
    CellSpacing="0" 
    AutoGenerateColumns="true"
    OnDataBound="gvTrades_DataBound">
</asp:GridView> 
protected void gvTrades_DataBound(object sender, EventArgs e)
{
    int myIndex = 0;
    foreach (DataControlFieldHeaderCell headerCell in gvTrades.HeaderRow.Cells)
    {
        if (headerCell.Text == "MyColumnName")
            break;

        myIndex++;
    }

    if (myIndex <= gvTrades.HeaderRow.Cells.Count - 1)
    {
        foreach (GridViewRow row in gvTrades.Rows)
        {
            row.Cells[myIndex].Text = String.Format("{0}%", row.Cells[myIndex].Text);
        }
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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