Using ParseControl and Subsequently Getting Specific Control Type

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.
 
J

Jordan S.

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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top