Formatting int to currency-formatted string in aspx page - asp.net

Suppose I have this label in my aspx page:
<asp:Label ID="savings" runat="server" Text='<%# Eval("savings")%>' />
Is there a way to format the text of a label as a currency-formatted string? I'm looking for something like this:
<asp:Label ID="savings" runat="server" Text='<%# Eval("savings").ToString("C")%>' />
When I run this I get the:
No overload for method 'ToString' takes 1 arguments
compilation error.
I know I can easily do this in my code-behind but I want to know if it's possible from the .aspx document.

Try this code:
<asp:Label ID="savings" runat="server" Text='<%# string.Format("{0:C}", Eval("savings"))%>' />

Try this code if you are dealing with string
<asp:Label ID="savings" runat="server" Text='<%# String.Format("{0:c}", Convert.ToDecimal(Eval("savings")))%>' />

The ToString(string) method only operates on numerical types, but Eval(string) returns object.
Cast the result to the correct type before calling the extension method on it, like this:
<%# ((decimal)Eval("savings")).ToString("C") %>

Late.. but useful
Anyone looking for Indian Currency Format or any other Currency use the CultureInfo class.
example:
(YourData).ToString("C2",CultureInfo.CreateSpecificCulture("in-IN"));
i would recommend that you convert the data you are trying to format to decimal in order to skip any overheads, also check this page for more culture combinations and more about formatting.

Related

ASP.NET WebForms: Format texts for strong typed ListView fields

I tha the following markup:
<asp:ListView ItemType="MyNamespace.MyEntity" runat="server" >
<listiview tags>
<asp:Label ID="lblDebtAmount" runat="server" Text="<%#:string.Format("
{0:C}",Item.Amount) %>"
</listiview tags>
</asp:ListView>
In the given example i'm trying to apply currency format to the text rendered by a label, but i'm after achieve this for text controls in general (Labels, Literal, Textbox, etc) . The problem is that the above produce the following server error:
"Analizer Error Mesage: Invalid Server Tag"
The same result if i try with the following:
<asp:Label ID="lblDebtAmount" runat="server" Text="<%#:string.Format("
{0:C}",Item.Amount.ToString("C")) %>"
Another approach, this time i get runtime exception:
<%# String.Format("{0:C}", Eval(Item.Amount.ToString() )) %>
DataBinding: 'System.Data.Entity.DynamicProxies... does not contains a
property named '500000,00'.
Another approach that i have tryied is formating the entity's property:
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Amount { get; set; }
That does not produce any error but neither got the text formated, the label just render the value without format
The only thing that seems to work is using the old way databinding:
<%# String.Format("{0:C}", Eval("Amount")) %>
But if i'm going to use strong typed binding for Webforms i dont want to be using strings to resolve properties value anymore:
I think this has to be dead easy, any thought?
Try switching from double quotes to single quotes for the text property, the way you currently have it ends the string early so the text property is actually just "<%#:string.Format("
<asp:ListView ItemType="MyNamespace.MyEntity" runat="server" >
<listiview tags>
<asp:Label ID="lblDebtAmount" runat="server" Text='<%#:string.Format("
{0:C}",Item.Amount) %>'
</listiview tags>
</asp:ListView>

ASP.NET Eval Byte Array as String

I am building a ListView from an EntityDataSource. There is a Byte[] field called Sha1Hash that I need to convert to a String type for a Hyperlink. This is a code snippet from ItemTemplate:
<asp:HyperLink ID="hl_Document" runat="server"
NavigateUrl='<%# string.Format("~/GetDocument.ashx?docId={0}", Eval("SHA1HASH") ) %>'
Text='<%# Eval("DOCUMENTNAME") %>' />
This is producing a URL like "~/GetDocument.ashx?docId=System.Byte[]", but it needs to be a hex string representing the value of the byte array. What would be the best approach to accomplish this? Ideally I would accomplish this entirely in the .aspx page rather than the code behind.
Update: I resolved this issue by using
NavigateUrl='<%# string.Format("~/GetDocument.ashx?docId={0}", BitConverter.ToString((byte[])Eval("SHA1HASH")).Replace("-", string.Empty) ) %>'
My problem was that I needed to cast Eval() to byte[]. It was being cast to string.
Depending on what format you want, you're probably looking for Convert.ToBase64String() or BitConverter.ToHexString().
I resolved this issue by using
NavigateUrl='<%# string.Format("~/GetDocument.ashx?docId={0}", BitConverter.ToString((byte[])Eval("SHA1HASH")).Replace("-", string.Empty) ) %>'
My problem was that I needed to cast Eval() to byte[].

how to call split method on designtime binding value

Hi all
I have a grid with some templatecolumn , now i want to bind to on object property.
one of these property is a string type that i want split it in design time.
my code is here, but i have error. i know my code is wrong. please help me if any one know the right option to do this.
<telerik:GridTemplateColumn DataField="FilePath" UniqueName="FilePath" HeaderText="نام فایل" >
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"FilePath.Split('-').Last();")%>
</ItemTemplate>
</telerik:GridTemplateColumn>
You need to cast our Eval's expression to a type of string and then call Split method:
<ItemTemplate>
<%# ((string)Eval(FilePath)).Split('-').Last() %>
</ItemTemplate>

casting problem of star rating?

I have an application with ajax star rating but when i am assigning value to CurrentRating from datatable then it showing error of "Specified cast is not valid".
I am using this code.
<asp:TemplateField HeaderText="Rating" SortExpression="CustomerRating">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "CustomerRating")%>'></asp:Label></a>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<cc1:Rating ID="Rating1" runat="server" CurrentRating='<%# Bind("CustomerRating") %>'
StarCssClass="ratingStar"
WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar"
EmptyStarCssClass="emptyRatingStar"
>
</cc1:Rating>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
Then its showing error CurrentRating='<%# Bind("CustomerRating") %>'.
I am taking refrence from these sites.
asp.net forum
Code Project
Same thing working on Code project.
The problem is most likely that the CustomerRating property of your data item is not of the correct data type. Rating expects an int. The Databinder does use reflection and attempts to automatically handle type conversions, but it has limits.
Unfortunatly there isn't enough information in your qustion to know what the actual runtime type of CustomerRating is, so I can't say why it can't be cast. My advise would be to explicitly cast or convert the property like so:
CurrentRating='<%# (string)Bind("CustomerRating") %>'
CurrentRating='<%# Bind("CustomerRating").ToString() %>'
CurrentRating='<%# (int)Bind("CustomerRating") %>'
If you can't convert it simply, or just need to get a debugger on it so you can figure out what the type is you can call out to a custom method in your code-behind instead (and you can attach a debugger there to so you can see the runtime type of the item:
CurrentRating='<%# MyCustomMethod(Eval("CustomerRating")) %>'
in code behind:
public string MyCustomMethod(object customerRating)
{
string rValue = ... //do whatever you need to do to customerRating to get a string out of it
// good place to set a breakpoint you you can examine what type customerRating actually is so you can figure out how best to convert it to something databinding can use
return rValue;
}

Formatting DataBinder.Eval data

How can I format data coming from a DataBinder.Eval statement in an ASPX page?
For example, I want to display the published date of the news items in a particular format in the homepage. I'm using the ASP.NET 2.0 Repeater control to show the list of news items.
The code for this goes like this:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<HeaderTemplate><table cellpadding="0" cellspacing="0" width="255"></HeaderTemplate>
<ItemTemplate>
<tr><td >
<a href='/content/latestNews.aspx?id=<%#DataBinder.Eval(Container.DataItem, "id") %>'>
<asp:Label ID="lblNewsTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "title") %>'></asp:Label>
</a>
</td></tr>
<tr><td>
<asp:Label ID="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate"))%>'></asp:Label>
</td></tr>
</ItemTemplate>
<FooterTemplate></table></FooterTemplate></asp:Repeater>
Is there a way I could call a custom method with the DataBinder.Eval value as its parameter (something like below)?
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
If yes, then where do I write the GetDateInHomepageFormat method? I tried out in the code behind page but got a run time error?
If this is not possible, is there a way to do inline formatting?
There is an optional overload for DataBinder.Eval to supply formatting:
<%# DataBinder.Eval(Container.DataItem, "expression"[, "format"]) %>
The format parameter is a String value, using the value placeholder replacement syntax (called composite formatting) like this:
<asp:Label id="lblNewsDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "publishedDate", "{0:dddd d MMMM}") %>'</label>
After some searching on the Internet I found that it is in fact very much possible to call a custom method passing the DataBinder.Eval value.
The custom method can be written in the code behind file, but has to be declared public or protected. In my question above, I had mentioned that I tried to write the custom method in the code behind but was getting a run time error. The reason for this was that I had declared the method to be private.
So, in summary the following is a good way to use DataBinder.Eval value to get your desired output:
default.aspx
<asp:Label ID="lblNewsDate" runat="server" Text='<%# GetDateInHomepageFormat(DataBinder.Eval(Container.DataItem, "publishedDate")) )%>'></asp:Label>
default.aspx.cs code:
public partial class _Default : System.Web.UI.Page
{
protected string GetDateInHomepageFormat(DateTime d)
{
string retValue = "";
// Do all processing required and return value
return retValue;
}
}
Hope this helps others as well.
Why not use the simpler syntax?
<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>
This is the template control "Eval" that takes in the expression and the string format:
protected internal string Eval(
string expression,
string format
)
http://msdn.microsoft.com/en-us/library/3d2sz789.aspx
You can use a function into a repeater like you said, but notice that the DataBinder.Eval returns an object and you have to cast it to a DateTime.
You also can format your field inline:
<%# ((DateTime)DataBinder.Eval(Container.DataItem,"publishedDate")).ToString("yyyy-MMM-dd") %>
If you use ASP.NET 2.0 or newer you can write this as below:
<%# ((DateTime)Eval("publishedDate")).ToString("yyyy-MMM-dd") %>
Another option is to bind the value to label at OnItemDataBound event.
This line solved my problem:
<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>
To format the date using the local date format use:
<%#((DateTime)Eval("ExpDate")).ToString("d")%>
How to Format an Eval Statement to Display a Date using Date Locale
Thanks to all. I had been stuck on standard format strings for some time. I also used a custom function in VB.
Mark Up:-
<asp:Label ID="Label3" runat="server" text='<%# Formatlabel(DataBinder.Eval(Container.DataItem, "psWages1D")) %>'/>
Code behind:-
Public Function fLabel(ByVal tval) As String
fLabel = tval.ToString("#,##0.00%;(#,##0.00%);Zero")
End Function
Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'
This works for the format as you want
<asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
</asp:Label>
You can use it this way in aspx page
<%# DataBinder.Eval(Container.DataItem, "DateColoumnName", "{0:dd-MMM-yyyy}") %>

Resources