C# 字符串格式不适用于 Eval
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14799951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String Formatting Not working with Eval
提问by LCJ
I have following expression for currency formatting inside an ASP.Net Gridview. It does not show dollar format though there is no error. What is the missing point here?
我在 ASP.Net Gridview 中有以下货币格式表达式。虽然没有错误,但它不显示美元格式。这里的缺失点是什么?
<%# String.Format("{0:C}", Convert.ToString(Eval("Amount")) ) %>
MARKUP
标记
<asp:GridView ID="grdFinancialAmount" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Emp ID">
<ItemTemplate>
<%# Eval("EmpID")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<%# String.Format("{0:C}", Convert.ToString(Eval("Amount")) ) %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
代码隐藏
protected void Page_Load(object sender, EventArgs e)
{
Financial fin1 = new Financial { EmpID = 1, Amount = 5678 };
Financial fin2 = new Financial { EmpID = 2, Amount = -111111 };
List<Financial> accounts = new List<Financial>();
accounts.Add(fin1);
accounts.Add(fin2);
grdFinancialAmount.DataSource = accounts;
grdFinancialAmount.DataBind();
}
public class Financial
{
public int EmpID { get; set; }
public int Amount { get; set; }
}
采纳答案by Matt
Why not just do either...
为什么不做任何...
<%# String.Format("{0:C}", Eval("Amount") ) %>
or
或者
<%# ((int)Eval("Amount")).ToString("C") %>
Looks to me like you are trying to convert Amount to a string twice, and you can't format a string as currency.
在我看来,您正试图将 Amount 转换为字符串两次,并且您无法将字符串格式化为货币。
回答by Royi Namir
try this :
尝试这个 :
<%# String.Format("{0:C}", int.Parse(DataBinder.Eval(Container.DataItem, "Amount").ToString())) %>
回答by Perisheroy
try this, works for me. (.NET 4.5 C#, in a gridview)
试试这个,对我有用。(.NET 4.5 C#,在网格视图中)
<%#Eval("Amout", "{0:C}").ToString()%>
回答by Ghasan
Eval
accepts a string format, and there is no need for these hacks.
Eval
接受字符串格式,不需要这些技巧。
As simple as: <%# Eval("Amount", "{0:C}") %>
就这么简单: <%# Eval("Amount", "{0:C}") %>