如何知道UserControl何时完成触发事件?

时间:2009-11-05 16:31:30

标签: c# asp.net user-controls event-handling delegates

我们有一个UserControl来处理用户取消,这在一些地方使用。这有几个输入字段和一个提交按钮。当他们提交时,用户的状态会更新,其他一些事情也会完成,并显示反馈信息。

在其中一个包含控件的页面上,在User通过UserControl成功取消提交之后,我们需要以某种方式通知页面,以便它可以调用其中一个方法并更新其显示[在这种情况下,用户的状态,即出席并现已取消]。

我们如何将这些链接起来?我猜的是涉及代表和事件处理人员的事情,但对他们没有多少经验,所以不知道我是否会走向死胡同...

一个非常hacky的解决方案是UserControl导致重定向,然后让页面监视会话或查询字符串参数等,但只是键入它让我颤抖所以必须非常多不得已。

如果需要更多信息,请询问,我会提供。

4 个答案:

答案 0 :(得分:2)

这应该很简单。将一个委托事件添加到UserControl,如下所示:

public event EventHandler UserCancelled;

然后,在取消方法结束时的用户控件中,只需调用委托:

if (this.UserCancelled!= null)
{
   this.UserCancelled(this, new EventArgs());
}

然后,只需在用户控件的aspx标记上添加一个处理程序:

OnUserCancelled="UserControl1_UserCancelled"

最后,在页面中添加处理程序:

protected void UserControl1_UserCancelled(object sender, EventArgs e)
{
    // Your code
}

答案 1 :(得分:1)

我认为你的直觉是正确的。您可以通过定义自定义事件和委托来解决此问题。这些方面应该做的事情:

public delegate void CancelledUserHandler();

public partial class UserCancellationControl : System.Web.UI.UserControl
{
    public event CancelledUserHandler UserCancelled;

    protected void CancelButtonClicked(object sender, EventArgs e)
    {
        // process the user's cancellation

        // fire off an event notifying listeners that a user was cancelled
        if (UserCancelled != null)
        {
            UserCancelled();
        }
    } 
}

public partial class MyPage : System.Web.UI.Page
{
    protected UserCancellationControl myControl;

    protected void Page_Load(object sender, EventArgs e)
    {
        // hook up the ProcessCancelledUser method on this page
        // to respond to cancellation events from the user control
        myControl.UserCancelled += ProcessCancelledUser;
    }

    protected void ProcessCancelledUser()
    {
        // update the users status on the page
    }
}

答案 2 :(得分:0)

最简单的方法是在UserControl上创建一个事件,表示已取消取消。在原始表单中为其添加处理程序,并在触发时更新显示。

答案 3 :(得分:-1)

如果您的表单是您自己设计的类,例如

public class MyForm : Form
{
   public void MyCustomRefresh()
   {
   }
}

然后,在您的自定义用户控件中,我会假设它在多个表单上使用,以允许记录取消,如您所述...然后,在任何事件/按钮的代码的最后,您可以执行类似< / p>

((MyForm)this.FindForm()).MyCustomRefresh()

因此,您可以使用“this.FindForm()”来获取表单,使用类型转换为您知道的自定义表单定义“MyCustomRefresh()”方法并直接调用它。没有代表需要。