I'd like to come back on the code I posted earlier in this Thread. The
code isn't good, so I baked some other code and I'd like to share it
with you all.
First of all, what is wrong with the code above. Well the function
searches for Control ID's using the Page's Request.Form object. The
Form however, does NOT contain ID's of control's that have their
enabled property set to false (or disabled attribute set at html side), while these Controls
could still be of importance.
After I while I came to the conclusion (but please correct me if I'm
wrong) that there isn't a 10 line solution to this problem. You'll have
to go through the complete Control tree by hand. And by hand means:
Building you're own copy of the tree and search it recursively. So
behold the ControlTree class.
/// <summary>Builds up a tree of <see cref="Control"/>
objects and enables specific searches through the tree.</summary>
class ControlTree
{
private ControlCollection _collection;
private List<ControlTree> _childNodes = new List<ControlTree>();
/// <summary>Constructor</summary>
/// <param name="collection">The <see
cref="System.Web.UI.ControlCollection"/> object to start the tree
with</param>
public ControlTree(ControlCollection collection)
{
this._collection = collection;
foreach (Control control in collection)
{
if (control != null && control.Controls != null)
this._childNodes.Add(new
ControlTree(control.Controls));
}
}
/// <summary>Finding and returning the controls who's ID ends with the id parameter.</summary>
/// <param name="id">The *id to search for.</param>
/// <returns>The matching control or null (Nothing in VB) when no control is found.</returns>
public Control FindControlEndingWith(string id)
{
Control match = null; // The reference to the matching control
foreach (Control control in _collection)
{
if (control !=
null && control.ID != null && control.ID.EndsWith(id))
{
if (match != null) throw new Exception("Duplicate
control found.");
match = control; // We've got a match
}
}
foreach (ControlTree node in this._childNodes)
{
Control control = node.FindControlEndingWith(id);
if (control != null)
{
if (match != null) throw new Exception("Duplicate
control found.");
match = control; // We've got a match
}
}
return match;
}
}
You initialize the tree with the Page's Controls object (a
ControlCollection). The old function that I wrote for my BasePage now
looks like this:
private ControlTree _controlTree;
public Control FindControlEndingWith(string id)
{
if (this._controlTree == null) this._controlTree = new ControlTree(this.Controls);
return this._controlTree.FindControlEndingWith(id);
}
A strong warning here, because I assume here that that Page's control
tree will never change after calling FindControlEndingWith(id) for the
first time. When it does, you will have to recreated the ControlTree on
every call (and that can cause performance to drop), or find a smart
way to indicate if the tree has changed.