简体   繁体   English

从Web用户控件调用父aspx页面的函数

[英]Call a function of parent aspx page from web user control

i have a aspx page on it i'm dynamically adding the web user controls in a placeholder. 我上面有一个aspx页面,我正在将Web用户控件动态添加到占位符中。 and know i have cancel button on the one user control and on click of that Cancel button i want to load other user control inside the aspx page (placeholder). 并且知道我在一个用户控件上有“取消”按钮,并且单击该“取消”按钮后,我想在aspx页面(占位符)中加载其他用户控件。

how can i do that, if i create an event handler in usercontrol then that become null. 我该怎么做,如果我在usercontrol中创建了一个事件处理程序,那么它将变为null。

thanks 谢谢

A user control should never, ever have any kind of dependency to the page where it lives. 用户控件永远不应该对它所在的页面有任何依赖。 Add an event to the control and fire it from the Cancel button event handler. 将事件添加到控件,然后从“取消”按钮事件处理程序中触发它。

public event EventHandler CancelClicked;

protected Cancel_Click(object sender, EventArgs e)
{
  if(CancelClicked != null)
  {
    CancelClicked(this, e);
  }
}

From your page, subscribe to the controls's CancelClicked event and do whatever operation should be done on that other user control. 在页面上,订阅控件的CancelClicked事件,然后对该其他用户控件执行任何操作。

I believe the best way to achieve this would to create an event in the user control that is fired when you need it to communicate, then in the page you can subscribe to this event. 我相信实现此目标的最佳方法是在用户控件中创建一个事件,该事件在您需要它进行通信时触发,然后可以在页面中订阅此事件。

Your User Control 您的用户控件

Put this in your control as an event variable. 将其作为事件变量放入控件中。

public event EventHandler CancelRequested;

Then in the cancel button click event : 然后在取消按钮中单击事件:

CancelRequested(this, new CommandEventArgs("CancelClicked", SomeVariable));

Your Page (or parent) 您的页面(或父页面)

Then subscribe to the event in the parent page like this (when you dynamically add it in): 然后像这样在父页面中订阅事件(当您动态添加事件时):

ctrlYourControl.CancelRequested += new EventHandler(ctrlYourControl_CancelRequested);

Declare the event handler : 声明事件处理程序:

void ctrlYourControl_CancelRequested(object sender, EventArgs e)
{
    // display other user control
}

Add this event to your user controls: 将此事件添加到用户控件中:

public event EventHandler CancelClicked;

Now, this method on your parent aspx page. 现在,在您的父aspx页面上使用此方法。

public void OnCancelClicked (object sender, EventArgs data)  
{  
    // do your stuffs like loading other controls and
    // whatever when event fired
}  

When you are loading your user control dynamically, add this: 在动态加载用户控件时,添加以下内容:

var someControl = LoadControl(@"~\SomeControl.ascx") as SomeControl;
someControl.CancelClicked += new EventHandler(OnCancelClicked);

And on your user controls: 并在您的用户控件上:

public void btnCancel_Click(object sender, EventArgs e)
{
    if(CancelClicked != null)
    {
        CancelClicked(this, e);
    }
}

This should do ! 这应该做!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM