如何引发用户控件的单独事件实例?

时间:2016-12-02 08:08:37

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

我有一个用户控件,当文件上传到它的内部FileUpload控件时会引发事件。当只有一个用户控件实例将事件注册到页面时,它可以正常工作。当我添加第二个实例时,第一个事件不再有效。如果我从第一个或第二个实例触发事件,它们都会运行UserControl2_FileSelected方法。我想为页面上的每个用户控件运行一个单独的方法。

页:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyUserControls.Default" %>

<%@ Register Src="~/Classes/Controls/FileUploader.ascx" TagPrefix="uc1" TagName="FileUploader" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <uc1:FileUploader runat="server" id="FileUploader1" Text="Uploader 1" />
    <uc1:FileUploader runat="server" ID="FileUploader2" Text="Uploader 2" />
</asp:Content>

页面代码背后:

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FileUploader1.FileSelected += new EventHandler(UserControl1_FileSelected);
            FileUploader2.FileSelected += new EventHandler(UserControl2_FileSelected);
        }

        protected void UserControl1_FileSelected(object sender, EventArgs e)
        {
            //handle event from instance 1
            System.Diagnostics.Debug.WriteLine("Control 1");
        }

        protected void UserControl2_FileSelected(object sender, EventArgs e)
        {
            //handle event from instance 2
            System.Diagnostics.Debug.WriteLine("Control 2");
}
}

后面的用户控制代码:

public partial class FileUploader : System.Web.UI.UserControl
    {
        public event EventHandler FileSelected;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if (this.FileUpload1.HasFile)
                {
                    this.FileSelected(this, e);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您需要使用Delegate,而不是EventHandler

在用户控件

private Delegate _FileSelected;
public Delegate FileSelected
{
    set { _FileSelected = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (FileUpload1.HasFile)
        {
            //invoke the command in the parent
            _FileSelected.DynamicInvoke(FileUpload1.FileName);
        }
    }

然后在包含控件的页面

delegate void FileSelected(string value);

protected void Page_Load(object sender, EventArgs e)
{
    //add the delegates to the usercontrol
    FileSelected fileSelected1 = new FileSelected(UserControl1_FileSelected);
    FileUploader1.FileSelected = fileSelected1;

    FileSelected fileSelected2 = new FileSelected(UserControl2_FileSelected);
    FileUploader2.FileSelected = fileSelected2;
}

private void UserControl1_FileSelected(string value)
{
    Label1.Text += "1: " + value + "<br>";
}

private void UserControl2_FileSelected(string value)
{
    Label1.Text += "2: " + value + "<br>";
}