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?
<%# 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; }
}
Eval(Object, String, String) Evaluates data-binding expressions at run time and formats the result as a string.
Imagine for example a GridView with a ItemTemplate and EditItemTemplate . If you use Bind or Eval in the ItemTemplate , there will be no difference. If you use Eval in the EditItemTemplate , the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.
The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function.
Eval function is used to bind data to control inside a DataBound control, but it cannot update the values back to the database. Bind function can be used to bind data to control inside a DataBound control and also it can update the values back to the database.
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.
Eval
accepts a string format, and there is no need for these hacks.
As simple as: <%# Eval("Amount", "{0:C}") %>
try this, works for me. (.NET 4.5 C#, in a gridview)
<%#Eval("Amout", "{0:C}").ToString()%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With