Using ParseControl and Subsequently Getting Specific Control Type

  • Thread starter Thread starter Jordan S.
  • Start date Start date
J

Jordan S.

Using .NET 3.5, I'm wondering how to get a control's specific type (e.g,.
"Button" and not simply "Control") after the control is inserted into a
control hierarchy - when ParseControl is used.

For example, I have the following code:

string str = "<table border=1><tr><td>Hello
World</td></tr><tr><td><asp:Button ID=\"TestButton\" onclick=\"b_Click\"
runat=\"server\" Text=\"Button\" /></td></tr><tr><td>Goodbye
Everybody!</td></tr></table>";
Control ctl = ParseControl(str);
this.form1.Controls.Add(ctl);

This code inserts an html table that contains a Button into the
form1.Controls collection.

My question: How can I subsequently retrieve a Button type reference to the
inserted Button?

What I'm trying to do is implement logic that walks the control tree looking
for any Button and TextBox objects that may have been inserted into the
control tree. This logic may or may not encounter Button and/or TextBox
controls - depending on the contents of the string passed to ParseControl.
This logic that walks the control tree does not (and cannot) know ahead of
time if there are actually any Button or TextBox objects in the Control
hierarchy. So I can't use FindControl to find any particular Button or
TextBox instances.

Thanks.
 
I found the answer:
In brief, you just cast the 'Control' typed object to the desired object
type, as in the following code.

There is really no mystery here and nothing at all complicated. The reason I
thought something was difficult was because I had a bug in my code in which
the recursive call passed the current control [in the recursive call] and
not the current child control of the current control. Consequently, the
recursive calls never went beyond the current control. Total error on my
part.

But for those interested, here is a method [sans bug] that will get the
first control of the type you want to retrieve from a control collection
[possibly populated via ParseControl]:
----------------------------------------------
private T FindFirstControlRecursive<T>(Control control) where T : Control
{
string theType = string.Empty;
foreach (Control subcontrol in control.Controls)
{
if (subcontrol is T)
{
return (T)subcontrol;
}
T nestedcontrol = FindFirstControlRecursive<T>(subcontrol);
if (nestedcontrol != null)
return nestedcontrol;
}
return null;
}
 
Back
Top