Adding Triggers dynamically on UpdatePanel for dynamially added controls

别说谁变了你拦得住时间么 提交于 2019-12-08 15:43:42

问题


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.


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/19807988/adding-triggers-dynamically-on-updatepanel-for-dynamially-added-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!