Question

How do I set a property of a user control in ListView's LayoutTemplate from the code-behind?

<asp:ListView ...>
<LayoutTemplate>
<myprefix:MyControl id="myControl" ... />
</LayoutTemplate>
...
</asp:ListView>

I want to do this:

myControl.SomeProperty = somevalue;

Please notice that my control is not in ItemTemplate, it is in LayoutTemplate, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.

Was it helpful?

Solution

To set a property of a control that is inside the LayoutTemplate, simply use the FindControl method on the ListView control.

var control = (MyControl)myListView.FindControl("myControlId");

OTHER TIPS

var control = (MyControl)myListView.FindControl("myControlId");

This will work but make sure you do it after the data bind or the LayoutTemplate will not have been created thus throwing an error.

Use the FindControl method on each ListViewItem.

var control = (MyControl)Item.FindControl("yourControlId");

This has been answered in this Stack Overflow question:
Access a control inside a the LayoutTemplate of a ListView

See the comment on the accepted answer by tanathos.

I know this was asked over a year ago, but it's one of the first results for the search term I used to get here, so I wanted to leave the answer for anyone else who stumbled upon it.

The layout gets created, and fires a LayoutCreated event that says the layout has been created in the system.

Then, you can use listview.FindControl to get a reference to that control.

In case you need the VB.net version, here it is:

Dim control = CType(myListView.FindControl("myControlId"), MyControl)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top