Patrick
Patrick

Reputation: 7712

Finding Dynamic controls in other Rows of a Repeater

I'm using a repeater to create a dynamic, database driven form.

Part of the required functionality is to be able to have dynamically driven drop down lists that depend on the values from previously selected drop downs to generate their values.

So If i'm creating a drop down list control and adding it to a row and assigning it an id, and i go to the next row, how do I get the value from the control in the previous row?

This is what I'm trying, but the .FindControl is returning null every time.

DropDownList toParentDDL = (DropDownList)rptDynamicForm.FindControl("ParentControlID");

The ID's are being set properly, and the id being placed in the find control method is proper as well.

Just another thought... When I'm adding the controls to the repeater, i'm doing so as such:

e.Item.FindControl("pnlQuestionAnswer").Controls.Add(toDropDown);

could it be that it is nested inside the panel?

To clear up any confusion. These controls are being created on ItemDataBound.

Solution:

Thanks to Tim's help. I finally realized what the problem was. I was looking for the control inside the repeater, and the repeater itself doesnt contain the control, the ITEMS contain the control I was looking for, and even though the items are in the repeater, it doesn't look IN the items. (I had it in my head that .findcontorl works like .find in jquery, which it doesn't)

to Fix the issue I simply did:

                    foreach (RepeaterItem toItem in rptDynamicForm.Items)
                    {
                        DropDownList toParentDDL = (DropDownList)toItem.FindControl("ParentControlID");

                        }

so now as long as it doesnt return null, it will contain the correct control.

Upvotes: 1

Views: 1040

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460128

You cannot search the repeater to find a control in one of its ItemTemplates. Their NamingContainer are their RepeaterItems not the Repeater itself. This makes sense since every item contains controls with the same ID as the previous/next item.

Therefore you need to get a reference to the previous item to find your control:

protected void rptDynamicForm_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
   switch (e.Item.ItemType) {
       case ListItemType.Item:
       case ListItemType.AlternatingItem:
          if (e.Item.ItemIndex != 0) {
             DropDownList toParentDDL = 
                (DropDownList)rptDynamicForm.Items[e.Item.ItemIndex - 1].FindControl("ParentControlID");
          }
          break;
    }
}

Upvotes: 3

Related Questions