简体   繁体   中英

Adding PostBackTrigger and AsyncPostBackTriggers to UpdatePanel for dynamically generated checkboxes with checkedChanged EventHandler

For more clear explanation here's my code on .asp file:

<asp:UpdatePanel ID="updPnlTabs" runat="server" >
   <Triggers>
    <asp:PostBackTrigger ControlID="btnSave" />
   </Triggers>
  <ContentTemplate>
   <asp:Panel ID="pnlCheckList" runat="server" style="margin-bottom: 10px;" CssClass="listingDummyTab">
   </asp:Panel>
  </ContentTemplate>
</asp:UpdatePanel>

On my .cs code, I dynamically created checkeboxes to the pnlCheckList like this:

CheckBox chkModuleID = new CheckBox();
chkModuleID.ID = drNew[def.ID].ToString();
chkModuleID.AutoPostBack = true;
chkModuleID.CheckedChanged += new EventHandler(chkID_OnRow_Check);
pnlCheckList.Controls.Add(chkModuleID);

Now my problem here is when I change the check boxes the whole page have to load instead of the content of the UpdatePanel . Note that the EventHandler for the dynamically created checkboxes is firing but not inside the UpdatePanel.

How can I add the ID 's of the dynamically created Controls in <Triggers> of the UpdatePanel ?

There is no way of adding dynamic (or programmatically created) controls to the markup, therefore, you must register the control with the ScriptManager after creating it.

Per the AsyncPostBackTrigger documentation , adding an AsyncPostBackTrigger control programmatically is not supported:

To programmatically register a postback control, use the RegisterAsyncPostBackControl method of the ScriptManager control. Then call the Update method of the UpdatePanel control when the control posts back.


Basically what you should be doing is registering the CheckBox control after creating it.

// original code
CheckBox chkModuleID = new CheckBox();
chkModuleID.ID = drNew[def.ID].ToString();
chkModuleID.AutoPostBack = true;
chkModuleID.CheckedChanged += new EventHandler(chkID_OnRow_Check);
pnlCheckList.Controls.Add(chkModuleID);

// register the control to cause asynchronous postbacks
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(chkModuleID);

Important: Inside of your chkID_OnRow_Check callback/eventhandler function, ensure you call UpdatePanel1.Update() .

Update 2013-02-20

Due to the my understanding of the exception you are receiving, consider making the CheckBox IDs unique.

// One possibility is this - assuming you don't require a consistent ID
chkModuleID.ID = String.Format("{0}-{1}", drNew[def.ID].ToString(), Guid.NewGuid().ToString("N"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM