Adding Triggers dynamically on UpdatePanel for dynamially added controls

love Computer science picture love Computer science · Nov 6, 2013 · Viewed 22.9k times · Source

I am Adding array Buttons to a simple panel dynamically which is located in an Update Panel, now I want to Add triggers for UpdatePanel on click event of these buttons. My codes is as below:

protected void AddButtons()
{
    Button[] btn = new Button[a];
    for (int q = 0; q < a; q++)
    {

        btn[q] = new Button();

        buttonsPanel.Controls.Add(btn[q]);
        btn[q].ID = "QID" + q;
        btn[q].Click += new EventHandler(_Default_Click);
        btn[q].Attributes.Add("OnClick", "Click(this)");

        AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
        trigger.ControlID = btn[q].ID;
        trigger.EventName = "Click";
        UpdatePanel2.Triggers.Add(trigger);                
    }
}

Now click event is not fired when i click on any of these bottons and buttons are getting removed.

Please note that these buttons are not available on Page_Init() method.

Answer

Maxim Kornilov picture Maxim Kornilov · Nov 17, 2013

You need to assign UniqueID instead of ID to AsyncPostBackTrigger.ControlID property. Try to use the following code:

AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = btn[q].UniqueID;
trigger.EventName = "Click";
UpdatePanel2.Triggers.Add(trigger);