UserControl Events Not Firing with Dynamically Created Button Control

J

jasinx

When I run this code it creates a button on an .aspx page. When I
click the button it seems to fire the events but I'm unable to capture
them in the function in the ascx codebehind. Any help? Thank Jason.

start ASCX codebehind -------------------------------------------

public partial class WebUserControl1 : System.Web.UI.UserControl
{

Button btn = new Button();

protected override void OnInit(EventArgs e)
{
btn.Text = "this works";
btn.ID = this.UniqueID + "$btn";
btn.Click += new EventHandler(btn_Click);
base.OnInit(e);
}

protected override void Render(HtmlTextWriter writer)
{

btn.RenderControl(writer);
base.Render(writer);
}

void btn_Click(object sender, EventArgs e)
{
throw new Exception("The method or operation is not
implemented.");
}

}

End ASCX codebehind -------------------------------------------

Start ASPX Codebehind -------------------------------------------

public partial class _Default : System.Web.UI.Page
{
WebUserControl1 ctrl;
protected void Page_Load(object sender, EventArgs e)
{
ctrl =
(WebUserControl1)LoadControl("WebUserControl1.ascx");
ctrl.ID = this.UniqueID;
Page.FindControl("divMain").Controls.Add(ctrl);

}
}

End ASPX Codebehind -------------------------------------------
 
G

gover

I'm quite onclear on this but i remember reading that when you re-create
user on each postback , the events dont get fired because the old button is
gone, and there is a new button created in its place. Try changin the code
to
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if(!IsPostBack)
{
btn.Text = "this works";
btn.ID = this.UniqueID + "$btn";
btn.Click += new EventHandler(btn_Click);
}
}
..This won't create a 'new' button each time.
(Just a guess)
 
G

gover

Hey, One other thing, I think You shold create your controls in
CreateChildControls. If you do it on InInit, you controls will probably be
overwritten. This may help(not sure of the syntax):
protected override void CreateChildControls(EventArgs e)
{
base.CreateChildControls(e);
if(!IsPostBack)
{
btn.Text = "this works";
btn.ID = this.UniqueID + "$btn";
btn.Click += new EventHandler(btn_Click);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top