Asked  6 Months ago    Answers:  5   Viewed   40 times

I have a complex asp.net form,having even 50 to 60 fields in one form like there is Multiview, inside MultiView I have a GridView, and inside GridView I have several CheckBoxes.

Currently I am using chaining of the FindControl() method and retrieving the child ID.

Now, my question is that is there any other way/solution to find the nested control in ASP.NET.

 Answers

88

If you're looking for a specific type of control you could use a recursive loop like this one - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx

Here's an example I made that returns all controls of the given type

/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control 
{
    private readonly List<T> _foundControls = new List<T>();
    public IEnumerable<T> FoundControls
    {
        get { return _foundControls; }
    }    

    public void FindChildControlsRecursive(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(T))
            {
                _foundControls.Add((T)childControl);
            }
            else
            {
                FindChildControlsRecursive(childControl);
            }
        }
    }
}
Tuesday, June 1, 2021
 
nhunston
answered 6 Months ago
40

Courtesy of Mr. Atwood himself, here's a recursive version of the method. I would also recommend testing for null on the control and I included how you can change the code to do that as well.

protected void Button1_Click(object sender, EventArgs e)
{
    if (TextBox1.Text != "")
    {
        Label Label1 = FindControlRecursive(Page, "Label1") as Label;
        if(Label1 != null)
            Label1.Text = "<b>The text you entered was: " + TextBox1.Text + ".</b>";
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label Label1 = FindControlRecursive(Page, "Label1") as Label;
    if (Label1 != null)
        Label1.Text = "<b>You chose <u>" + DropDownList1.SelectedValue + "</u> from the dropdown menu.</b>";
}

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id) return root;
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null) return t;
    }
    return null;
}
Friday, June 11, 2021
 
ojrac
answered 6 Months ago
71

Generally I implement a "FindInPage" or recursive FindControl function when you have lots of control finding to do, where you would just pass it a control and it would recursively descend the control tree.

If it's just a one-off thing, consider exposing the control you need in your API so you can access it directly.

public static Control DeepFindControl(Control c, string id)
{
   if (c.ID == id)
   { 
     return c;
   }
   if (c.HasControls)
   {
      Control temp;
      foreach (var subcontrol in c.Controls)
      {
          temp = DeepFindControl(subcontrol, id);
          if (temp != null)
          {
              return temp; 
          }
      }
   }
   return null;
}
Tuesday, June 15, 2021
 
BlueNile
answered 6 Months ago
59

FindControl only searches direct children of the container. Since you are starting off at the page level, you will need to recurse through the child UpdatePanel control to get to your btnAdd control.

Have a look here for an example how to do do this.

Edit: I'm not sure I understand why you are 'looking' for your button in this manner, since there is only one static button on the screen - you wouldn't need to use FindControl in this case.

<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />

(or in code, btnAdd.OnClick += new EventHandler(btnAdd_Click);)

Even if you had multiple Buttons in your form added dynamically, you could wire ALL of them up to the same Button Click handler, in which case sender would then contain the Button Control which was clicked. You would typically use FindControl to scrape the data out of the dynamically added Input controls (text box etc), rather than to see which control caused the Postback (as 'sender' in an appropriate event handler would be easier)

Edit 2: You can add the buttons dynamically just like your other controls

    Button myButton = new Button();
    myButton.Text = "Click Me";
    myButton.Click += new EventHandler(btnAdd_Click);
    myPlaceHolder.Controls.Add(myButton); 

If you want all the controls that you've added already to 'stay' in between postbacks then enable viewstate on the page and on the controls, and then make sure that you only add the controls once without postback, in OnInit:

   base.OnInit(e);    
   if (!IsPostBack)
   { // ... Add controls here

You can keep the state of 'mycount' in a hidden field (in the same updatepanel, and with viewstate enabled) - you'll need to parse it to an int each time. Or you can use SessionState to track it.

Friday, August 6, 2021
 
Ben
answered 4 Months ago
Ben
23

The FindControl method only looks in the current control for children.

If you don't know where in the page hierarchy the controls are, you'll need to do a recursive search - which is likely if you're using a templated control such as the TabContainer.

As I've posted previously to a similar answer:

private Control FindControlRecursive(Control rootControl, string controlID)
{
  if (rootControl.ID == controlID) {
    return rootControl;
  }

  foreach (Control controlToSearch in rootControl.Controls)
  {
    Control controlToReturn = 
      FindControlRecursive(controlToSearch, controlID);
    if (controlToReturn != null) { 
      return controlToReturn;
    }
  }

  return null;
}

Once you've got your control, you should cast it using as and then check for null just in case it's not quite what you were expecting:

var tabContainer = FindControlRecursively(myPage, "Workflow_TabContainer")
                 as AjaxControlToolkit.TabContainer

if (null != tabContainer) {
  // Do Stuff
}
Saturday, November 27, 2021
 
gMale
answered 3 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share