Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Triggers dynamically on UpdatePanel for dynamially added controls

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.

like image 742
love Computer science Avatar asked Nov 06 '13 09:11

love Computer science


2 Answers

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);
like image 177
Maxim Kornilov Avatar answered Sep 18 '22 23:09

Maxim Kornilov


I came across this post when I was attempting to dynamically add triggers to an update panel which contained a gridview. I have buttons in the gridview and defining the trigger in the page doesn't work as a unique ID for each button is generated when each row is created.

Generating the trigger like such;

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

did not work for me. The control could not be found, however when using the RegisterPostbackControl or the RegisterAysncPostbackControl commands it worked.

The end example is as follows;

    protected void BankAccountDocumentGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           LinkButton linkButton = (LinkButton)e.Row.Cells[3].FindControl("DocumentsDownloadButton");
           ScriptManager.GetCurrent(Page).RegisterPostBackControl(linkButton);
        }
    }

I figured that the original poster or others who come across this post may benefit from my findings.

like image 21
Atters Avatar answered Sep 20 '22 23:09

Atters