c# - 将 PostBackTrigger 和 AsyncPostBackTriggers 添加到 UpdatePanel 以使用 checkChanged EventHandler 动态生成复选框

标签 c# asp.net

更清晰的解释这里是我在 .asp 上的代码文件:

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

在我的 .cs代码,我像这样动态地为 pnlCheckList 创建了复选框:
CheckBox chkModuleID = new CheckBox();
chkModuleID.ID = drNew[def.ID].ToString();
chkModuleID.AutoPostBack = true;
chkModuleID.CheckedChanged += new EventHandler(chkID_OnRow_Check);
pnlCheckList.Controls.Add(chkModuleID);

现在我的问题是当我更改复选框时,整个页面必须加载而不是 UpdatePanel 的内容.请注意,动态创建的复选框的 EventHandler 正在触发,但不在 UpdatePanel 内。

如何添加 ID的动态创建的 Controls<Triggers>UpdatePanel ?

最佳答案

无法将动态(或以编程方式创建的)控件添加到标记中,因此,您必须使用 ScriptManager 注册控件。创建之后。

AsyncPostBackTrigger documentation ,添加一个 AsyncPostBackTrigger不支持以编程方式控制:

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.



基本上你应该做的是在创建 CheckBox 控件后注册它。
// 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);

重要提示:您的内部 chkID_OnRow_Check回调/事件处理函数,确保你调用 UpdatePanel1.Update() .

更新 2013-02-20

由于我对您收到的异常的理解,请考虑使 CheckBox ID 唯一。
// 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"));

关于c# - 将 PostBackTrigger 和 AsyncPostBackTriggers 添加到 UpdatePanel 以使用 checkChanged EventHandler 动态生成复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14742426/

相关文章:

c# - 为什么 char 的 Convert.ToInt32 返回 ascii 码?

C# - 在混合使用文件和文件夹的线程中锁定(线程安全)

c# - ASP.NET 4 自定义成员资格提供程序表

c# - 如何编辑所有特殊 html 标签的属性(如 a)

javascript - 在 asp.net 中隐藏更新面板中的 div

c# - EF + 通用存储库 + 加载相关实体 : only explicit load works

c# - 使用语句未处理的异常

c# - 找到给定的不等式集的最大子集,它有一个解决方案

asp.net - 有没有办法将外部 URL 分配给超链接而不附加 http ://or https://(ie, 协议(protocol))?

c# - 将 using 子句添加到项目中 - 初学者