Question

Trying to add buttons programmatically to a webform. Some work - others don't. In the code below I add btnY and btnX in the Page_Load. These both work - they show on the page and fire the event and the code in the event handler works.... In the page load I also run bindData which gets a DataTable and uses the data to create controls. in the example I am only creating Button. These buttons will appear on the page correctly but when clicked they only do a postback .. the code in the event handler doesn't work - does it get called? The event handler is the same for all the buttons. Any ideas why or how I can make it work?

protected void Page_Load(object sender, EventArgs e)
{
    PlaceHolder1.Controls.Add(btn("btnY", "Y"));
    Pages P = new Pages();
    bindData(P.DT);
    PlaceHolder1.Controls.Add(btn("btnX", "X"));
}
Button btn(string id, string text)
{
    Button btn1 = new Button();
    btn1.ID = id;
    btn1.Text = text;
    btn1.Click += new System.EventHandler(this.btn_click);
    return btn1;
}
protected void bindData(DataTable dt)
{
    foreach (DataRow row in dt.Rows)
    {
        render(Convert.ToInt32(row["PageKey"]));
    }
}
protected void render(int pageKey)
{
    PlaceHolder1.Controls.Add(btn("btn_" + pageKey.ToString(), "Edit"));
}

protected void btn_click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    string id = btn.ID;
    Pages P = new Pages();
    bindData(P.DT);
    lt.Text = "ID=" + id;

}
Was it helpful?

Solution

Never mind .. figured it out .. example above should work, my actual code had a if (!Page.PostBack) that caused the problem

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top