[英]Get properties value from parent user control
I want to create a method to get a value from the parent user control but PropertyInfo
can't get the value from the parent control and throws an exception. 我想创建一个从父用户控件获取值的方法,但
PropertyInfo
无法从父控件获取值并引发异常。 I think this is happening because it's not the object's actual type. 我认为这是发生的,因为它不是对象的实际类型。
I am using .NET 2 so I can't use dynamic keyword. 我正在使用.NET 2,所以不能使用dynamic关键字。
Is there any way to do this? 有什么办法吗?
public object GetFromPar(Control parent, string propertyName, Type parentType)
{
while (parent != null)
{
if (parent.GetType().IsSubclassOf(parentType))
{
PropertyInfo info = parent.GetType().GetProperty(propertyName);
return info.GetValue(parent, null);
}
else
{
parent = parent.Parent;
}
}
return null;
}
And this is how i call this function. 这就是我所谓的函数。
this.GetFromPar(this.Parent, "Name", typeof(InfoControl));
InfoControl is a user control that was a parent of LoginPanelControl (this). InfoControl是作为LoginPanelControl(此)的父级的用户控件。
Thank you in advance. 先感谢您。
PropertyInfo info = (typeof(parent.GetType())).GetProperty(propertyName);
如果您知道父项的类型,则可以将其替换为parent.GetType()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.