ASP.Net

Using fieldcontrols in a ListView

Google+ Pinterest LinkedIn Tumblr

When you want to use a fieldcontrol like a Text, Link or Image control in a ListView you need to specify a datasource. By not specifying a datasource Sitecore looks at the current item. Which in a ListView is not the right one. So you need so set the datasource in code-behind or use an Eval expression in code-before.

When you want you use the code-behind option you need to raise an eventhandler which triggers the ItemDataBound handler.In that event you want to get the values of the current item. So you need to cast the ListViewDataItem to an Sitecore item.

For instance:

Code-before

<asp:ListView ID="ListView1" runat="server">
<layoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</layoutTemplate>
<itemTemplate>

<h1><sc:Text ID="Text1" Field="Title" runat="server" /></h1>

<asp:HyperLink ID="BlogPostLink" runat="server">Read more...</asp:HyperLink>

</itemTemplate>
</asp:ListView>

Code-behind

ListView1.DataSource = BlogManager.GetAllBlogPosts(Sitecore.Context.Item.ID);
ListView1.ItemDataBound += new EventHandler<listViewItemEventArgs>(ListView1_ItemDataBound);
ListView1.DataBind();

The datasource of the ListView is a generic list of items (In this case that will be all children matching a specific templateid). Then create an new EventHandler to bind the controls in the ItemTemplate to the current item.

void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{

Item objEntry = (Item)((ListViewDataItem)e.Item).DataItem;

Text txt = (Text)e.Item.FindControl("Text1");
txt.DataSource = objEntry.ID.ToString();
}

Instead of the above way I could also use an Eval in the code-before, but then I’m going to use C# in a way I don’t want to.
For example:

<h1><sc:Text ID="Text1" DataSource='<%#Eval("ID") %>' Field="Title" runat="server" /></h1>

So why would I use this “hard” way, instead I could just create the controls in C#. Well when I am working on a Sitecore project, usually I do all .Net stuff and a frontend developer creates the html and css. So when he wants to edit the html structure it is still possible for him, and there is no need for him to look in the code-behind file.

Write A Comment