1

I have a Placeholder and I have a dynamically created panel in the placeholder, I also have some dynamically added radio buttons in the panel, now I can usefindControl() to find the radio buttons if they are direct children of the placeholder.

I've literally spent the whole of yesterday trying to find them when they are the child elements of the Panel. How is there a way to do this?

Here's my code below:

PlaceHolder1.Controls.Add(myPanel); //add the panel to the placeholderenter code here
myPanel.Controls.Add(myRadioButton); //add the radiobutton to the panel
VDWWD
  • 35,079
  • 22
  • 62
  • 79
mthakhy
  • 21
  • 6
  • 1
    it's been asked, you're looking for recursive [`FindControl()`](http://stackoverflow.com/questions/4955769/better-way-to-find-control-in-asp-net) – Bagus Tesa Dec 02 '16 at 09:48

2 Answers2

0

You should make method that recursively searches for a control using it's Id. That mean that the method will search for a control inside of (in your case) placeholder. If method finds control, it will return it. If not, it will go search every placeholder's subcontrol, going "deeper". And then, if nothing is found, it will search one more level down, in every placeholder subcontrols' subcontrol etc.)

private Control FindControl(string ctlToFindId, Control parentControl)
{
    foreach (Control ctl in parentControl.Controls)
    {
        if (ctl.Id == ctlToFindId)
            return ctl;
    }

    if (ctl.Controls != null)
    {
        var c = FindControl(ctlToFindId, ctl);
        if (c != null) return c;
    }

    return null;
}

and then use it like this:

Control ctlToFind = FindControl(myRadioButton.Id, Placeholder1);
if (ctlToFind != null)
{
    //your radibutton is found, do your stuff here
}
else
{
    // not found :(
}
Nino
  • 6,931
  • 2
  • 27
  • 42
0

Finding Controls recursive is an option, but it also has a couple of down-sides.

If you know the ID's of all the controls you can just use FindControl

RadioButtonList myRadioButton = PlaceHolder1.FindControl("Panel1").FindControl("RadioButtonList1") as RadioButtonList;
Label1.Text = myRadioButton.SelectedValue;

But you will need to give your dynamically added controls an ID.

Panel myPanel = new Panel();
myPanel.ID = "Panel1";

RadioButtonList myRadioButton = new RadioButtonList();
myRadioButton.ID = "RadioButtonList1";

PlaceHolder1.Controls.Add(myPanel);
myPanel.Controls.Add(myRadioButton);
Community
  • 1
  • 1
VDWWD
  • 35,079
  • 22
  • 62
  • 79