Jur Jur - 7 days ago 5
ASP.NET (C#) Question

Findcontrol on Repeater can't find control

I'm trying to dynamically add click events to a table in the items of a repeater, with server-side code below. However, the Findcontrol can't find the control in the item... what am I doing wrong??

rownr = 0;
foreach (RepeaterItem ri in Lijst.Items)
{
string targ = "javascript:return GoAanvraag(" + rownr.ToString() + ");";
Table tb1 = ((Table) ri.FindControl("ItemTabel"));
tb1.Attributes.Add("onclick", targ);

rownr++;
}


Repeater code is:

<asp:Repeater ID="Lijst" runat="server" DataSourceID="SqlDataSource2"
OnItemDataBound="Lijst_ItemDataBound"
>
<HeaderTemplate>
</HeaderTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
<ItemTemplate>

<table ID="ItemTabel" style="width:100%">
<tr>

<td style="width:100%">
<asp:Label ID="Regel" runat="server"></asp:Label>
</td>
<td style="width:100%">
<asp:Label ID="Plancode" runat="server" font-size="20px" align=right></asp:Label>
</td>
<asp:Button ID="btnGoAanvraag" runat="server" visible="false"/>
</tr>

</table>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>

Answer

Couple of things here.

First, your table is not a server-side control. To make it one, add runat attribute:

<table ID="ItemTabel" style="width:100%" runat="server">

That said, it is weird to handle clicks on table itself. Did you actually mean any controls inside the table?

Second, it is not clear when you are running this code. This got to be in ItemDataBound event or later, as before that controls in item templates do not exist. And if it is inside ItemDataBound, there is no reason to iterate over all rows. ItemDataBound is raise once per row/item, and you have an item reference in the event args, so you can update just that item only.