Search code examples
c#asp.netasp.net-ajaxupdatepanel

How to set UpdatePanel to automatically update while registering AsyncPostBackTrigger programmatically?


I have a Button which will trigger an UpdatePanel, but it is in a different container so if I put my code like below :

<asp:UpdatePanel ID="uptxtQuickSearch" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false" style="height: 100%;">
    <ContentTemplate>
        <asp:TextBox ID="txtQuickSearch" CssClass="textinput" onmouseover="this.select()" onfocus="this.select()" onkeydown="QuickSearch()" runat="server"></asp:TextBox>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnSearchFilter" />
    </Triggers>
</asp:UpdatePanel>

There will be a runtime server error : "A control with ID 'btnSearchFilter' could not be found for the trigger in UpdatePanel 'uptxtQuickSearch'."

So I've to register it on the Page_load event with ScriptManager :

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterAsyncPostBackControl(btnSearchFilter);

but in this case, I still have to update the UpdatePanel manually by using Update() method on the end of btnSearchFilter_click event. Is there any way to update the panel automatically while registering the trigger on the code-behind?


Solution

  • I've found a solution for this issue. It turns out that you don't really need to register the control using RegisterAsyncPostBackControl method.

    you just need to add the trigger on Page_Init event and use the control.UniqueID if the control cannot be found on the runtime.

    So the aspx will be like this :

    <asp:UpdatePanel ID="uptxtQuickSearch" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false" style="height: 100%;">
        <ContentTemplate>
            <asp:TextBox ID="txtQuickSearch" CssClass="textinput" onmouseover="this.select()" onfocus="this.select()" onkeydown="QuickSearch()" runat="server"></asp:TextBox>
        </ContentTemplate>
    </asp:UpdatePanel>
    

    and in code-behind :

    protected void Page_Init(object sender, EventArgs e)
    {
        uptxtQuickSearch.Triggers.Add(new AsyncPostBackTrigger() { ControlID = btnSearchFilter.UniqueID });
    }