It has been a while that I have not coded so I was trying to get the properties from usercontrols that have been added dynamically.
I have created this code but would like to know if this is a good way or is there another better way of find out the added usercontrols?
if (PlaceHolder1.HasControls())
{
foreach (Control uc in PlaceHolder1.Controls)
{
if (uc.GetType().Name.ToLower() == "spinner_ascx")
{
Label1.Text += ((Spinner)c).Name + "<br />";
}
}
}
You don't need to compare the name if you already know the type of the control:
if (PlaceHolder1.HasControls())
{
foreach (Control uc in PlaceHolder1.Controls)
{
if (uc is Spinner)
{
Label1.Text += ((Spinner)uc).Name + "<br />";
}
}
}
But yes, if you want to access Name
and Name is only a property on the Spinner
class, you need to cast it to the appropriate object.
If you created these user controls, a good idea would be to make sure they all inherit from a base class, eg
public abstract class MyControl : UserControl {
public string Name {get;set;}
}
public class Spinner : MyControl {
}
That way, you don't need to test for each UserControl you want, just the parent class:
if(uc is MyControl) {
Label1.Text += ((MyControl)uc).Name + "<br />";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.