日期:2014-05-18  浏览次数:20396 次

怎样调用一个 动态创建的用户自定义控件 里的某个方法或事件?
怎样调用一个 动态创建的用户自定义控件 里的某个方法或事件?

protected void Page_Load(object sender, EventArgs e)
{
  var a = LoadControl("001.ascx");
  a.ID = "UC001";
  this.Controls.Add(a);
}

protected void Button1_Click(object sender, EventArgs e)
{
  var a = this.FindControl("UC001"); //这里竟然为null
  想在这里调用PageLoad事件里创建的自定义控件001.ascx中的方法或者事件应该怎么做?
}

------解决方案--------------------
C# code

protected override void OnInit(EventArgs e)
    {

         var a = LoadControl("001.ascx"); 
         a.ID = "UC001"; 
        form1.Controls.Add(tb);

        base.OnInit(e);
    }

------解决方案--------------------
<%@ Page Language="C#" %>
<%@ Reference Control="~/Controls/Spinner.ascx" %>
<script runat="server">
private ASP.Spinner Spinner1
 
protected void Page_Load(object sender, EventArgs e)
{
Spinner1 = (ASP.Spinner)LoadControl("~/Controls/Spinner.ascx");
}

protected void Button1_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(Spinner1);
}
</script>

<html>
<head id="Head1" runat="server">
<title>Load User Control Programmatically</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<br />
<asp:Button ID="Button1" runat="server" 
Text="Click to Add User Control" 
OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>