Question

Following these two threads: How can I create an Array of Controls in C#.NET? Cannot Access the Controls inside an UpdatePanel

I current have this:

ControlCollection[] currentControlsInUpdatePanel = new ControlCollection[upForm.Controls.Count];
foreach (Control ctl in ((UpdatePanel)upForm).ContentTemplateContainer.Controls)
{
    currentControlsInUpdatePanel.
}

currentControlsInUpdatePanel does not have an add or insert method. why does the first link i post allow that user to .add to his collection. This is what I want to do, find all the controls in my upForm update panel. but i dont see how i can add it to my collection of controls.

Was it helpful?

Solution

I don't think this code makes sense. You are creating an array of ControlCollection objects and trying to store Control objects in it. Furthermore, since currentControlsInUpdatePanel object is an array, there will not be an Add() method available on that object.

If you want to use the Add() method, try creating currentControlsInUpdatePanel as a List object.

Example:

List<Control> currentControlsInUpdatePanel = new List<Control>();
foreach(Control ctl in ((UpdatePanel)upForm).ContentTemplateContainer.Controls)
{
    currentControlsInUpdatePanel.Add(ctl);
}

If you want to continue to use an array to store the Control objects, you will need to use the index value to set your objects in the array.

Example:

Control[] currentControlsInUpdatePanel = new Control[((UpdatePanel)upForm).ContentTemplateContainer.Controls.Count];
for(int i = 0; i < upForm.Controls.Count; i++)
{
    currentControlsInUpdatePanel[i] = ((UpdatePanel)upForm).ContentTemplateContainer.Controls[i];
}

OTHER TIPS

The UpdatePanel's child controls collection is a special collection that contains only one child control: its template container. It is then that control that contains all the child controls of the UpdatePanel (such as a GridView or Button).

As it is noted in the other questions linked to in the question, walking the child control tree recursively is the best way to go. Then, when you've found the spot to which you need to add controls, call Controls.Add() in that place.

My suggestion would be a different approach: place an <asp:PlaceHolder> control in the UpdatePanel and give it a name and add controls to that. There should be no particular advantage to accessing the controls collection of the UpdatePanel itself, and then you wouldn't have to dig through implementation details of the controls (which, while they are unlikely to change, can make code much more difficult to read).

Try to use

ControlCollection collection = ((UpdatePanel)upForm).ContentTemplateContainer.Controls;

This gives you all the controls in that control collection. From there you can use CopyTo to copy it to the array you need:

Control[] controls = new Control[collection.Length];
collection.CopyTo(controls , 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top