Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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?

like image 975
Mark Avatar asked Feb 18 '23 14:02

Mark


1 Answers

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"));
like image 189
Jesse Avatar answered Apr 25 '23 19:04

Jesse