使用Eval格式化ASP.NET C#数据绑定中的百分比

时间:2013-04-30 13:24:33

标签: c# asp.net

数据库中有一个col声明为十进制4精度3.我需要将这个数乘以100(我在存储过程查询中这样做)并将其显示为十进制,后面只有重要的零小数点。如果结果值小于1%,我认为应该在小数之前显示0 。显示应包含%标记。例如:

 100 %
 99.1 %
 0.1 %
 56 %
 0 %

网页正在使用数据绑定:

 <asp:Label ID="lblTMLY_POL_HLDER_NOTC_PCT" runat="server" Text='<%# Eval("DECIMAL_COL_PREC_4_SCALE_3") %>'></asp:Label>

我想我可能更容易在Data Bound Item中处理它,并在那里使用字符串格式化函数。理想情况下,我想知道要使用的标记中的格式字符串以及如何在后面的代码中处理它。

  <asp:Label ID="lblTMLY_POL_HLDER_NOTC_PCT" runat="server" Text='<%# Eval("DECIMAL_COL_PREC_4_SCALE_3","{00:??????}") %>'></asp:Label>

1 个答案:

答案 0 :(得分:3)

这是你在找什么?

enter image description here

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField HeaderText="Id" DataField="Id" />
        <asp:BoundField HeaderText="Name" DataField="Name" />
        <asp:BoundField HeaderText="Actual Value" DataField="Total" />
        <asp:BoundField HeaderText="Using Bound Field" DataField="Total" 
            DataFormatString="{0:0.### %}" />
        <asp:TemplateField HeaderText="Using Eval">
            <ItemTemplate>
                <asp:Label runat="server" ID="Label1" 
                    Text='<%# string.Format("{0:0.### %}", Eval("Total")) %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

private class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Total { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    var items = new List<Item>
        {
            new Item {Id = 1, Name = "One", Total = 1.0M},
            new Item {Id = 2, Name = "Two", Total = 0.2M},
            new Item {Id = 3, Name = "Three", Total = 0.03M},
            new Item {Id = 4, Name = "Four", Total = 0.004M},
            new Item {Id = 5, Name = "Five", Total = 0.0005M},
            new Item {Id = 6, Name = "Six", Total = 0.00006M},
        };

    GridView1.DataSource = items;
    GridView1.DataBind();
}