Formatting DataBinder.Eval data - asp.net

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}") %>

Related

Formatting int to currency-formatted string in aspx page

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.

Customize label text in grid view template field

I want to show "N/A" text in grid view label if value is not available in database and if it is available, then the value should be displayed instead of "N/A".
How can I customize my label?
This is the code that I have written to get the value.
<asp:Label ID="lblCineRunFrom" runat="server" Text='<%# Eval("CineRunFrom") %>'></asp:Label>
This works:
<asp:Label id="dada" runat="server" Text='<%# string.Format("{0}",string.IsNullOrEmpty(Eval("CineRunFrom").ToString())?"N/A":Eval("CineRunFrom")) %>' ></asp:Label>
You may use this: Text='<%# Eval("CineRunFrom")?? "N/A" %>'
Add a new function in code behind & call it from HTML code, check sample code below.
Code
Private Function GetDisplayText(ByVal CineRunFrom As String) As String
'Do whatever you want here and return text to dispaly as required
End Function
HTML
<asp:Label ID="lblCineRunFrom" runat="server" Text='<%# GetDisplayText(Eval("CineRunFrom")) %>'></asp:Label>

Calling a property or member function of a string object inside of a ListView

I'm having some trouble calling a property or a method on a databound string object inside of a ListView. See this example:
<asp:ListView runat="server" ID="FullInfoListView">
<LayoutTemplate>
<table class="tablestripe" width="100%">
<asp:Placeholder runat="server" ID="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr valign="top" runat="server" Visible='<%# !string.IsNullOrEmpty((string)Eval("Phone")) %>'>
<td><strong>Phone:</strong></td>
<td><span runat="server" Visible='<%# ((string)Eval("Phone")).Length == 4 %>'>x</span><%# Eval("Phone") %></td>
</tr>
</ItemTemplate>
</asp:ListView>
This line:
<%# ((string)Eval("Phone")).Length == 4 %>'>
is what is giving me trouble. If I remove the .Length everything works fine. If I leave it in there my code throws an "Object reference not set to an instance of an object." exception on the line where I call the DataBind() method on the ListView in my code behind. This same behavior occurs with .ToLower() as well.
EDIT
I think I got this figured out. Thanks for those of you who suggested moving this out to a method in the code behind to help with debugging. The problem was related to a null reference...go figure :) I thought that if the table row wasn't visible that none of the logic inside would get evaluated, but I think due to the fact that it is databound the logic is evaluated anyway. So simply changing the above line to the following fixed the problem:
<%# Eval("Phone") != null && ((string)Eval("Phone")).Length == 4 %>'>
I would consider using a Label instead of a <span>. Instead of casting it to string, just use the ToString() function instead, and wrap the entire expression in parentheses to ensure that it's evaluating as a boolean:
<asp:Label ID="Label1" runat="server" Visible='<%# (Eval("Phone").ToString().Length >= 4) %>' Text="X" />
If the above doesn't fix your problem, you can always add a method in the code behind to do this:
<asp:Label ID="Label1" runat="server" Visible='<%# CheckLength(Eval("Phone").ToString()) %>' Text="X" />
Code-behind:
public bool CheckLength(string value)
{
return value.Length >= 4;
}
Move the compound code to code-behind method. For example the
'<%# ((string)Eval("Phone")).Length == 4 %>'
becomes
'<%# IsPhoneSpanVisible( (string)Eval( "Phone" ) ) %>'
with
protected bool IsPhoneSpanVisible( string Phone )
{
// provide your logic here
}
This way you'll be easily able to debug your code.

Tuncate string in ASP.NET using VB.NET

I made a function to truncate a string in the code behind file. But how do i use it in the aspx file?
This is the textbox:
<asp:TemplateField HeaderText="page" HeaderStyle-Wrap="true">
<ItemTemplate>
<a href='<%# makepageURL( Eval("page") )%> '>
<%# Eval("page")%>
</a>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtpage" TextMode="SingleLine" Rows="1" Width="100%" runat="server" Text='<% #Bind("page") %>' />
</EditItemTemplate>
</asp:TemplateField>
And this is my function:
Public Function TrimString(ByVal Value As String, ByVal Length As Integer) As String
If Value.Length > 20 Then
Return Value.Substring(Value.Length - (20 - 3)) + "..."
End If
Return Value
End Function
It's not an issue of how to use it, but actually when to use it?
If you had a regular span, you could do this:
<span><%: TrimString("somestring") %></span>
But this is a TextBox your dealing with (user input).
When should it truncate?
On Form Submit? (that would make sense).
As they type (well then you'd need to use JavaScript).
By the looks of your code snipper, your using a FormView.
So i wouldn't be calling it from the ASPX (which the equivalent of executing code during Page Render), i would be calling it during the Edit/Submit event, server-side event handler.
In other words, truncate the value the user put in, after they have submitted the form and before you persist to the database.

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;
}

Resources