Nov
26
2008

Using fieldcontrols in a ListView

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

[sourcecode language="html"]




Read more…



[/sourcecode]

Code-behind
[sourcecode language="csharp"]
ListView1.DataSource = BlogManager.GetAllBlogPosts(Sitecore.Context.Item.ID);
ListView1.ItemDataBound += new EventHandler (ListView1_ItemDataBound);
ListView1.DataBind();
[/sourcecode]

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.

[sourcecode language="csharp"]
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();
}
[/sourcecode]

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:
[sourcecode language="html"]

About the Author:

Leave a comment

Who am I

My name is Mark van Aalst and I work as a Solution Architect at Sitecore. I have 6+ years of experience developing applications on top of Sitecore.