我必须在子usercontrol中使用父usercontrol方法的结果。如何在子控件中找到方法?
答案 0 :(得分:11)
存在用户控件以使我们的代码更可重用,用户控件可以放在任何页面中,某些页面可能有这两个用户控件,有些页面没有,所以你不能确保页面会有两个用户控件。 在我看来,最好的方法是使用事件。这个想法如下:子usercontrol引发一个事件,放置此用户控件的页面处理此事件并调用父用户控件的事件,这样,您的代码仍然可以重用。
因此,儿童控制的代码将是以下
public partial class Child : System.Web.UI.UserControl
{
// here, we declare the event
public event EventHandler OnChildEventOccurs;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// some code ...
List<string> results = new List<string>();
results.Add("Item1");
results.Add("Item2");
// this code says: when some one is listening this event, raises this and send one List of string as parameters
if (OnChildEventOccurs != null)
OnChildEventOccurs(results, null);
}
}
页面需要处理此事件的发生,如此
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// the page will listen for when the event occurs in the child
Child1.OnChildEventOccurs += new EventHandler(Child1_OnChildEventOccurs);
}
void Child1_OnChildEventOccurs(object sender, EventArgs e)
{
// Here you will be notified when the method occurs in your child control.
// once you know that the method occurs you can call the method of the parent and pass the parameters received
Parent1.DoSomethingWhenChildRaisesYourEvent((List<string>)sender);
}
}
最后是在父控件中执行某些操作的方法。
public void DoSomethingWhenChildRaisesYourEvent(List<string> lstParam)
{
foreach (string item in lstParam)
{
// Just show the strings on the screen
lblResult.Text = lblResult.Text + " " + item;
}
}
这样,您的网页就会充当事件的协调者。
答案 1 :(得分:-1)
修改强>
你可以创建这样的方法来获得子控件中的parentcontrol
public ofparentcontroltype GetParentControl(Control ctrl)
{
if(ctrl.Parent is ofparentcontroltype)
{
return ((ofparentcontroltype)this.Parent);
}
else if (ctrl.Parent==null)
return null;
GetParentControl(ctrl.Parent);
}
调用方法就像下面的
ofparentcontroltype parent = GetParentControl(this);
if(parent!=null)
var data = ((ofparentcontroltype)this.Parent).methodtocall();
在usercontrol的代码隐藏中执行类似的操作
if(this.Parent is ofparentcontroltype)
{
var data = ((ofparentcontroltype)this.Parent).methodtocall();
}
点击此处查看示例: Access Parent Control's Method from a Child Control