views:

2137

answers:

5

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.

A: 

Use the FindControl method on each ListViewItem.

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

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");
+1  A: 

This has been answered in this Stack Overflow question:
http://stackoverflow.com/questions/433846/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.

tgittos
A: 

Hey,

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.

Brian
A: 
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.

Ben Rabidou