12

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.

John Rudy
  • 37,282
  • 14
  • 64
  • 100
Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138

6 Answers6

18
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
  • 355
  • 2
  • 5
12

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

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.

Community
  • 1
  • 1
tgittos
  • 344
  • 2
  • 4
1

Use the FindControl method on each ListViewItem.

var control = (MyControl)Item.FindControl("yourControlId");
chakrit
  • 61,017
  • 25
  • 133
  • 162
0

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 Mains
  • 50,520
  • 35
  • 148
  • 257
0

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

Dim control = CType(myListView.FindControl("myControlId"), MyControl)
Jeff
  • 1,362
  • 14
  • 17