Mohsen Sarkar
Mohsen Sarkar

Reputation: 6040

How to access controls inside repeater?

I have placed a TextBox inside repeater but I don't know what will be the ID to access those TextBoxes. So how I should access them ?

    <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
        <ItemTemplate>
            <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" AutoPostBack="true" ></asp:TextBox>
        </ItemTemplate>
    </asp:Repeater>

No FindControl please !

I want something similar to following code to access.

TextBox1.Text = "Hi";

Upvotes: 1

Views: 4552

Answers (4)

Colin
Colin

Reputation: 1846

You can use Repeater.ItemDataBound

<asp:Repeater id="Repeater1" OnItemDataBound="R1_ItemDataBound" runat="server">

Upvotes: 0

Matt
Matt

Reputation: 133

The shortest way, imho, is to iterate through all items of the repeater, find the desired control and do whatever you want with it. Example, in VB.NET

 For Each item As RepeaterItem In Repeater1.Items
     Dim temporaryVariable As TextBox = DirectCast(item.FindControl("TextBox1"), TextBox)
     temporaryVariable.Text = "Hi!"
 Next

But remember, you have to this after Repeater1.DataBind()

Upvotes: 0

Ripside
Ripside

Reputation: 153

The typical way, without a lot of recursion with FindControl (which isn't very efficient) is to wire up the OnItemDataBound even on the repeater, and in the code behind access the data row's individual elements. You pretty much have to use FindControl - but in this case you don't need to recurse into the controls collection.

void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {

      // This event is raised for the header, the footer, separators, and items.

      // Execute the following logic for Items and Alternating Items.
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {

         if (((Evaluation)e.Item.DataItem).Rating == "Good") {
            ((Label)e.Item.FindControl("RatingLabel")).Text= "<b>***Good***</b>";
         }
      }
   }   

Upvotes: 0

hackp0int
hackp0int

Reputation: 4161

I would suggest you to do it like so...

// another way to search for asp elements on page


 public static void GetAllControls<T>(this Control control, IList<T> list) where T : Control
        {
            foreach (Control c in control.Controls)
            {
                if (c != null && c is T)
                    list.Add(c as T);
                if (c.HasControls())
                    GetAllControls<T>(c, list);
            }
        }

Upvotes: 1

Related Questions