How to cast listview object - asp.net

I'm wondering how to cast a listview object to a datetime. Is there a way to do this on front end markup page?
Here's my code below from part of the listview functionality. This code below doesn't work properly.
<asp:ListView ID="listviewAttachments" runat="server">
<ItemTemplate>
<tr class="announcementPost">
<td class="posted">
<h6>Convert.ToDateTime(Eval("DateModified")).Day<span><asp:Label ID="Label1" runat="server" Text='<%# Convert.ToDateTime(Eval("DateModified")).Month %>' /> </span></h6>
</td>

You are not casting a ListView object to DateTime. What you are doing there is trying to cast one of your properties to DateTime
Try this:
<%=Convert.ToDateTime(Eval("DateModified")).Day %>

Related

Repeater: databind server-side ID in item control?

When binding a datasource to a Repeater control, is it possible to databind to the ID property of a server-side control inside the ItemTemplate? like so:
<asp:Repeater ID="rptToolTips" runat="server">
<ItemTemplate>
<telerik:RadToolTip ID="tt<%# Eval("Name") %>" ClientIDMode="Static" runat="server">
<div class="tip">
<div class="segName">Segment #<%# Eval("Name") %></div>
<div>Flow:<%# Eval("Flow", "{0:N}") %></div>
</div>
</telerik:RadToolTip>
</ItemTemplate>
</asp:Repeater>
...here I'm trying to set the RadToolTip's ID property to "tt[name-value]". I've tried a few variants but they're invalid:
ID="tt<%# Eval("Name") %>"
ID='tt<%# Eval("Name") %>'
ID="tt<%# Eval('Name') %>"
It's not possible. A server control's ID is set at the time it's being created or at design time. Once it's set you cannot reset it during the data binding.
But, if you are trying to use this ID value in JQuery or JavaScript you could employ the following hack.
Add a custom property to your control (give it any name you like and in this case I'll use myId)
myId='<%# Eval("Name") %>'
No you can find this element by this myId property
Hope this helps.
Try this to assign ID
ID=' "tt" + <%# Eval("Name") %>'
Also see this answer by me to one of the questions at SO for another way (using pure JavaScript's this object rather than using a custom property to get the clientID) of doing this.
Just thought of keeping these linked for future reference.

Binding Repeater with Dictionary<string, Dictionary<int,[object]>

I am new to .NET, so I'm struggling with this. I have a content page, with a repeater control. I have a Dictionary, which is a Dictionary<string, Dictionary<int,[object]>>. I want the value of the controls inside the repeater control to get it from the object attributes - Candidate Name, would be object.CandName, candidate phone would be object.Phone etc.
I am not sure how to use Eval for this type of Dictionary. Most of the examples point to Eval("Value"), but it is not giving the correct value for me. Kindly help!
<asp:Content ID="Content2" ContentPlaceHolderID="content" Runat="Server">
<div id="rcontent">
<table>
<tr>
<td>
<asp:Label ID="lblerror" runat="server" Text="" Visible="true" CssClass="alert"></asp:Label>
</td>
</tr>
</table>
<div id ="rptdiv">
<asp:Repeater ID="Repeater1" runat="server" EnableViewState="false">
<ItemTemplate>
<div id="Div3">
<table class="GridViewStyleNoBorder" width=750px cellspacing="0" border="0" >
<tr>
<td class="PagerStyle" colspan="4">
<asp:Label ID="lblName" Runat="server"
Text='<%= Need the value of the [object].objectproperty from dictionary here %>' />
</td>
</tr>
</table>
</div>
This is my Page_Load code behind - BLDecision is my business layer code, which returns the dictionary and dictionary values are correct. I checked them in debug mode.
Code Behind:
Dictionary(int, Dictionary(int, InterviewFeedback)) ;
CandIntDetails = new Dictionary(int, Dictionary(int, InterviewFeedback))();
BLDecision objBLDecision = new BLDecision();
int ReqCategoryID = 0;
if (Request.QueryString["ReqCategoryID"] != null)
ReqCategoryID = int.Parse(Request.QueryString["ReqCategoryID"].ToString());
CandIntDetails = objBLDecision.GetCandidatesforReqCategory(ReqCategoryID);
Repeater1.DataSource = CandIntDetails;
Repeater1.DataBind();
Should I use from codebehind, can I not do Eval('<% ....%>') in the aspx page?
Thanks in advance for your help.
You cannot do it with only one repeater. Since you have a container inside a container, you need a Repeater inside a repeater:
<asp:Repeater ID="Repeater1" runat="server" EnableViewState="false">
<ItemTemplate>
<div id="Div3">
<table class="GridViewStyleNoBorder" width=750px cellspacing="0" border="0" >
<asp:Repeater ID="Repeater2" runat="server" DataSource='<%# Eval("Value")' >
<ItemTemplate>
<tr>
<td class="PagerStyle" colspan="4">
<asp:Label ID="lblName" Runat="server"
Text='<%# Eval("Name") %>' />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
If CandIntDetails is a Dictionary<int, Dictionary<int, InterviewFeedback>>, you need to extract from that the specific collection you want to use as the data source of your repeater. The reason why is because you want to render a collection of InterviewFeedback objects, which CandIntDetails is not. CandIntDetails probably looks something like this:
{
46: {
0: [InterviewFeedback],
1: [InterviewFeedback],
2: [InterviewFeedback]
}
}
It's not clear from your post what the keys are for the inner or outer dictionaries, so this is speculative. If the outer key is the the category ID (not sure why GetCandidatesforReqCategory would return something like that), and if you don't care about the inner dictionary keys, you can extract your data source like this:
Repeater1.DataSource = CandIntDetails[ReqCategoryID].Values;
That will make your data source a straight collection of InterviewFeedback objects. Once that's your data source, you can Eval to access the properties of the InterviewFeedback objects.

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.

Is it possible to do custom grouping in the ASP.NET ListView control?

You can only define a GroupItemCount in the ListView, but what if you want to do grouping based on a property of the items in the data source? Sort of an ad-hoc group by. The data source is sorted on this property.
I have seen some examples where some markup in the ItemTemplate was conditionally show, but I want to leverage the GroupTemplate if possible.
Is this possible?
When I had to add basic group headings in a repeater I did so with a Literal control in the ItemTemplate:
<asp:Literal runat="server" Text='<%# GetGroupHeading(Eval("Group")) %>' />
The 'GetGroupHeading' method in the code kept track of the previous group heading and sent back '<h2>Group Name</h2>', or an empty string if we were on the same group as the previous item. As I said though, I did this on a Repeater, so not sure if it will cover what you need for a ListView.
Yes Nick gave a great lead. Here's my code-behind
Dim sCategory_Descr As String
Function GetGroupHeading(ByVal sGroupName As String) As String
Dim sReturn As String
If sCategory_Descr <> sGroupName Then
sCategory_Descr = sGroupName
sReturn = "<H5>Category: " & UCase(sGroupName) & "</H5>"
Else
sReturn = ""
End If
Return sReturn
End Function
And my item_template
<ItemTemplate>
<tr>
<td style="background-color:#ccc;" colspan="2" id="tdCategory_Placeholder" runat="server" >
<asp:Label Font-Bold="true" ID="Literal1" runat="server" Text='<%# GetGroupHeading(Eval("Category_Descr")) %>' />
</td>
</tr>
<tr>
<td >
<asp:DynamicControl1 />
</td>
<td >
<asp:DynamicControl2 />
</td>
</tr>
</ItemTemplate>
Try this article from 4 Guys from Rolla: Using ASP.NET 3.5's ListView and DataPager Controls: Grouping Data with the ListView Control

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