Reputation:
I am doing following code to generate dynamic buttons with their click event.
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.form1.Controls.Add(bt);
}
}
protected void bt_click(object sender, EventArgs e)
{
Label1.Text = "Clicked";
}
but i am not able to generate the click event of that dynamically generated button. Can any one help me?
Upvotes: 0
Views: 2470
Reputation: 2709
My previous submission was on WinForms which I have deleted. Here is the one on asp.net
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
CreateButton(i);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void bt_click(object sender, EventArgs e)
{
Button btn = sender as Button;
Label1.Text = btn.Text + " Clicked";
}
private void CreateButton(int id)
{
Button bt = new Button();
bt.Text = "ok" + id.ToString();
bt.Click += new EventHandler(bt_click);
bt.ID = "btn" + id.ToString();
this.Form.Controls.Add(bt);
}
Upvotes: 1
Reputation: 6911
For ASP.NET to be able to execute your event, control which triggered it should also exist on your page after postback. What is going on with your code looks like this:
It was all ok up till now, now problem occurs
General rule is that if you're adding controls dynamically and you want them to trigger events, you should do it latest in Page_Load. For more details please read ASP.NET Page Life Cycle Overview
Upvotes: 2
Reputation: 15881
you need to add this code in either page load or page_init event of page. then only you can access it. How to add controls dynamically asp.net
protected void Page_Load()
{
for (int i = 0; i < int.Parse(textBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.Controls.Add(bt);
}
}
Upvotes: 0
Reputation: 1891
I'm not sure if its your problem, but you might want to set the location property of eachbutton you add like:
bt.Location = new Point(25,i+55);
Upvotes: 0
Reputation: 8786
You need to set the position of those new buttons, or they will cover each other.
Upvotes: 0