代码之家  ›  专栏  ›  技术社区  ›  Geri Langlois

如何从动态创建的usercontrol引发事件

  •  1
  • Geri Langlois  · 技术社区  · 16 年前

    如何从动态创建的用户控件引发事件?

    下面是我正在尝试的代码,其中Bind是一个公共事件处理程序

    protected indDemographics IndDemographics;
    protected UserControl uc;
    override protected void OnInit(EventArgs e)
    {
        uc = (UserControl)LoadControl("indDemographics.ascx");
        IndDemographics.Bind += new EventHandler(test_handler);
        base.OnInit(e);
    }
    

    先谢谢你。。。

    3 回复  |  直到 16 年前
        1
  •  3
  •   Stephen Wrighton    16 年前

    首先,您需要确保在usercontrol的代码中定义了事件。

    public class MyUserControl
      Inherits UserControl
    
      Public Event Bind(sender as object, e as EventArgs)
    
      public sub SomeFunction()
         RaiseEvent Bind(me, new EventArgS())
      End Sub
    End Class
    

    Runat=Server

    如果没有,则需要确保使用虚拟路径作为ASCX文件的位置。(在您的示例中,您将使用 “~/indDemographics.ascx” 如果ASCX位于网站的根目录下)。此时,您需要将其添加到页面(或占位符或其他容器对象)。

    不管您以何种方式实例化UserControl实例,都会将事件处理程序与类实例的事件相关联。例如:

    Dim btn As New Button;
    AddHandler btn.Click, AddressOf MyButtonClickEventHandler
    

    使用LoadControl引用时,对象的实例位于 变量在本例中,您声明了两个对象,UC作为UserControl类型,indDemographics作为indDemographics类型。

    当您使用LoadControl时,您正在实例化indDemographics的一个实例并将其分配给UC。当您尝试将事件处理程序分配给IndDemographics变量时,它实际上从未被实例化。

    最终,您的代码应该更符合以下内容:

    protected indDemographics IndDemographics;
    override protected void OnInit(EventArgs e)
    {
        indDemographics = LoadControl("~/indDemographics.ascx");
        IndDemographics.Bind += new EventHandler(test_handler);
        base.OnInit(e);
    }
    
        2
  •  1
  •   ctacke    16 年前

        3
  •  1
  •   Geri Langlois    16 年前

    谢谢斯蒂芬让我走上正轨。下面是C#中的最终工作代码:

    protected indDemographics IndDemo;
    override protected void OnInit(EventArgs e)
    {
        Control c = LoadControl("~/indDemographics.ascx");
        IndDemo = (indDemographics) c;
        IndDemo.Bind += new EventHandler(test_handler);
        place1.Controls.Add(IndDemo);
        base.OnInit(e);
    }
    

    将泛型控件强制转换到indDemographics类中很重要。在那之后,其他一切都很好。