Reputation: 853
I have a simple test custom control that I have created and am trying to figure out why the click event will not fire. below is the code. I simply create an instance of the control on a test page with
Page_Load of .aspx page that consumes the control protected void Page_Load(object sender, EventArgs e) { Page.Form.Controls.Add(new TestControl()); }
The page does a post back but it does not pick up the click event in the user control. Please explain what I am doing incorrectly or a better way to approach this with a specific pattern etc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
namespace WorldOfTest
{
public class TestControl : WebControl { private Button btn;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
protected override void EnsureChildControls()
{
btn = new Button();
this.Controls.Add(btn);
base.EnsureChildControls();
}
protected override void CreateChildControls()
{
btn.Click += new EventHandler(btn_Click);
btn.Text = "test button";
base.CreateChildControls();
}
void btn_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
btn.RenderControl(writer); ;
}
}
}
Thank You for your help
Upvotes: 0
Views: 1192
Reputation: 108957
You have to add your btn
to Controls
collection like this
protected override void EnsureChildControls()
{
this.btn = new Button();
Controls.Add(btn);
base.EnsureChildControls();
}
EDIT:
Seems to be working fine for me once I add the button to the control's collection.
I tried this
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Controls.Add(new Tester());
}
and I get this
Upvotes: 0