一段时间以来,我没有编码,所以我试图从动态添加的用户控件中获取属性。
我已经创建了这段代码,但是想知道这是一个好方法还是找到添加的用户控件的另一种更好的方法?
if (PlaceHolder1.HasControls())
{
foreach (Control uc in PlaceHolder1.Controls)
{
if (uc.GetType().Name.ToLower() == "spinner_ascx")
{
Label1.Text += ((Spinner)c).Name + "<br />";
}
}
}
如果您已经知道控件的类型,则无需比较名称:
if (PlaceHolder1.HasControls())
{
foreach (Control uc in PlaceHolder1.Controls)
{
if (uc is Spinner)
{
Label1.Text += ((Spinner)uc).Name + "<br />";
}
}
}
但是,是的,如果您要访问Name
并且Name只是Spinner
类的一个属性,则需要将其强制转换为适当的对象。
如果创建了这些用户控件,那么一个好主意是确保它们都从基类继承,例如
public abstract class MyControl : UserControl {
public string Name {get;set;}
}
public class Spinner : MyControl {
}
这样,您无需为每个所需的UserControl进行测试,只需对父类进行测试:
if(uc is MyControl) {
Label1.Text += ((MyControl)uc).Name + "<br />";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句