JaGo
JaGo

Reputation: 257

Objects within asp.net repeater aren't found by my code behind?

So in my asp.net application I have a repeater, but any object inside that repeater can't be found from my code behind. Here's an example:

Markup

  <asp:Repeater ID="repeater_id" runat="server"
            DataSourceID="ExampleSource">
            <HeaderTemplate>
                <table id="table_id">
                    <thead>
                        <tr>
                            <th>Example</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <asp:Label runat="server" ID="MyLabel" />
                    </td>
                </tr>
            </ItemTemplate>

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

And in my Page Load I'm trying to add an attribute like this:

C#

protected void Page_Load(object sender, EventArgs e)
        {
            MyLabel.Attributes.Add("Example","Example");
        }

However, in my aspx.cs page, "MyLabel" is highlighted as a build error, with a description "The name 'MyLabel' does not exist in the current context." Anbody know what that could be? If MyLabel is before or after the repeater, it works just fine.

Anybody know what my problem is? Please explain as clearly as possible, I'm new to coding.

Edit: Mistyped my coding within the question. Fixed now.

Upvotes: 1

Views: 259

Answers (1)

ekad
ekad

Reputation: 14614

You need to loop through repeater_id.Items and find the label like below

foreach (RepeaterItem ri in repeater_id.Items)
{
    Label MyLabel = (Label)ri.FindControl("MyLabel");
    MyLabel.Attributes.Add("Example","Example");
}

Upvotes: 1

Related Questions