如何格式化网格视图页脚和ItemTemplate中的数字格式(“###,###。000”)

时间:2015-03-11 11:45:31

标签: html css asp.net

如何格式化网格视图页脚和ItemTemplate中的数字格式(" ###,###。000")

html中的

页脚:

       <FooterTemplate>
        <asp:Label ID="totallblCredAmount" runat="server" />
     </FooterTemplate> 

footer代码:

 if (e.Row.RowType == DataControlRowType.Footer)
   {

       Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
       totallblCAmount.Text = ViewState["TotalPric"].ToString();

       Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
       totallblCredAmount.Text = ViewState["TotalPrice"].ToString();

   }

ItemTemplate html:

 <asp:TemplateField HeaderText="credit">
            <ItemTemplate>
                 <asp:Label  runat="server" Text='<%#(Eval("credit"))%>'></asp:Label>
            </ItemTemplate>  
        </asp:TemplateField>

1 个答案:

答案 0 :(得分:0)

您必须将字符串值解析为decimal,然后才能使用decimal.ToString("###,###.000")。但是,如果您将doubledecimal值存储在ViewState中,则只需相应地对其进行投射,而不是使用ToString将其转换为string。< / p>

所以也许:

if (e.Row.RowType == DataControlRowType.Footer)
{
   Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
   decimal pricValue = (decimal)ViewState["TotalPric"];
   totallblCAmount.Text = pricValue.ToString("###,###.000");

   Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
   decimal priceValue = (decimal)ViewState["TotalPrice"];
   totallblCAmount.Text = priceValue.ToString("###,###.000");
}

如果存储字符串,则必须按前面所述解析它:

 string stringPriceValue = (string)ViewState["TotalPrice"];
 decimal priceValue = decimal.Parse( stringPriceValue );
 totallblCAmount.Text = priceValue.ToString("###,###.000");

我建议不要将十进制数值存储为字符串,这不仅是因为你总是需要解析它,而且主要是因为你对本地化问题持开放态度。


根据您在ItemTemplate中如何格式化标签的评论中的问题。如果你想在aspx上这样做,你可以这样做:

<asp:Label  runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "credit", "{0:###,###.000}") %>' ID="LblCredit"></asp:Label>

另一种方法是使用代码隐藏。我会使用RowDataBound

protected void GrdidView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // note that i've assigned an ID to the label
        Label lblCredit = (Label) e.Row.FindControl("LblCredit");
        DataRow row = ((DataRowView) e.Row.DataItem).Row;  // maybe you need to change the type of the dataitem
        double credit = row.Field<double>("credit");
        lblCredit.Text = credit.ToString("###,###.000");
    }
}