I generated two buttons and put them into a list of buttons..
List<Button> buttons = new List<Button>();
Button pgs=new Button
for(int i=0;i<2;i++)
pgs.Width = 20;
pgs.Command += obtainTopicsPerPage_Click;
pgs.CommandName = i.ToString();
pgs.Text =i.ToString();
btns.Add(tPage.ToString());
buttons.Add(pgs);
I added the buttons to a placeholder, and they appear on the page.
The event that they have is the following:
void obtainTopicsPerPage_Click(Object sender, CommandEventArgs e)
{
foreach (var item in tPages)
{
if (item.Key == e.CommandName)
{
foreach (var posts in item.Value)
{
posts.ExecuteAll();
}
}
}
MyButtonTable();
}
It doesn't matter what the functions do (they simply create tables and make it look like posts in a forum page)..
Now when the user clicks any one of the buttons that appear on the screen..none of the events are being triggered.. I put a breaking point inside the eventhanlder method and the web application doesn't reach there.
All I am concerned is why the buttons aren't attached to the event handling method that I gave them..why when I set the break point in the event it never triggers.
What should happen, when a button is clicked.. the event should should be triggered first, and the page should load second. But that doesn't happen..what happens is the button event being skipped, and the page load event is triggered with every postback after the button click..
Updated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
string[] d;
protected void Page_Load(object sender, EventArgs e)
{
d = new string[] { "dfadfas", "daads", "dasda", "dads" };
Buttons();
}
List<Button> btns;
public void Buttons()
{
btns = new List<Button>();
for (int i = 0; i < 20; i++)
{
Button d = new Button();
d.Text = "Click me";
d.Click += Me_Click;
btns.Add(d);
}
function();
}
public void function()
{
foreach (var item in btns)
{
PlaceHolder1.Controls.Add(item);
}
}
public int i { get{object o=ViewState["i"];return (o==null)?0:(int)o;} set{ViewState["i"]=value;} }
public void Me_Click(object sender, EventArgs e)
{
foreach (var item in d)
{
Label da= new Label();
da.Text = "d"+i+++"<br/>";
this.Controls.Add(da);
}
}
}
The working code above..
I tested by saving the buttons list with Session. Here I recreate the buttons at PreInit
void Page_PreInit(object sender, EventArgs e)
{
List<Button> btn = (List<Button>)Session["Buttons"];//debugging shows 2 buttons
if (btn != null)
{
foreach (var item in btn)
{
item.Width = 20;
item.Command += obtainTopicsPerPage_Click;
item.CommandName = tPage.ToString();
item.Text = tPage.ToString();
}
}