Jur Jur - 1 year ago 112
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);


Repeater code is:

<asp:Repeater ID="Lijst" runat="server" DataSourceID="SqlDataSource2"
<hr />

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

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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download