Click to See Complete Forum and Search --> : Adding events to a dynamic generated button


j.a.z
April 30th, 2003, 06:53 AM
hi

i got a little problem about adding events to a dynamic generated button....

look at the following code.
the 10 buttons will be generated correctly, but when clickin on it, nothing happens... the added event will NOT be raised???

why???
thanx for any answer...
Regards, jaz


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace TestApp
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.PlaceHolder PlaceHolder1;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
for( int i=0; i < 10; i++ )
{
Button btnMod = new Button();
btnMod.ID= "Test" + Convert.ToSingle(i);
btnMod.Text= "Test" + Convert.ToSingle(i);
btnMod.Click += new System.EventHandler(this.btnX_Click);
PlaceHolder1.Controls.Add(btnMod);
}
}

private void btnX_Click(object sender, System.EventArgs e)
{
Response.Write("dynamic click!");
}
}
}

fizch
April 30th, 2003, 12:48 PM
I am not real familiar with ASP.NET, but I know that in VB.NET when you are declaring an event you have to tell the function to handle a specific event for a specific control.

j.a.z
May 2nd, 2003, 06:38 AM
I know, thats a difference between VB.NET and C#... in C# you dont have to do it!

but i found the error...
the eventhandler works, wenn added to the button directly in the Page_Load() event. :)