[英]how to access properties of dynamically created user controls?
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. 但是可以,如果您要访问
Name
且Name仅是Spinner
类的一个属性,则需要将其Spinner
转换为适当的对象。
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: 这样,您无需为每个所需的UserControl进行测试,只需对父类进行测试:
if(uc is MyControl) {
Label1.Text += ((MyControl)uc).Name + "<br />";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.