在asp.net中动态创建更新面板时出错

时间:2016-03-26 11:11:11

标签: c# asp.net

我正在尝试动态创建更新面板。 我想动态创建一个复选框和一个更新面板。更新面板包含一个不可见的标签,更新面板的触发器是复选框。应该发生的是,当用户选中复选框时,updatepanel的标签应该是可见的 这是我的.aspx页面 -

      <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default8.aspx.cs" Inherits="Default8" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:PlaceHolder ID="LocalPlaceHolder" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

这是我的.aspx.cs页面,我试图通过它动态创建更新面板,该面板在复选框的checkedchanged事件中刷新 -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default8 : System.Web.UI.Page
{
    Label NewLabel;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            System.Web.UI.HtmlControls.HtmlGenericControl createDiv =
                    new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
            createDiv.ID = "createDiv";
            CheckBox ch = new CheckBox();
            ch.Attributes.Add("runat", "server");
            ch.Text = "Add to compare";
            ch.ID = "ch";
            ch.AutoPostBack = true;
            ch.CheckedChanged += new System.EventHandler(ch_CheckedChanged);
            createDiv.Controls.Add(ch);
            AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
            trigger.ControlID = ch.ID;
            trigger.EventName = "CheckedChanged";
            UpdatePanel up = new UpdatePanel();
            up.ID = "up";
            up.Triggers.Add(trigger);
            NewLabel = new Label();
            NewLabel.Visible = false;
            NewLabel.ID = "NewLabel";
            NewLabel.Text = "added";
            up.ContentTemplateContainer.Controls.Add(NewLabel);
            createDiv.Controls.Add(up);
            ScriptManager1.RegisterAsyncPostBackControl(up);
            LocalPlaceHolder.Controls.Add(createDiv);
        }
    }
    protected void ch_CheckedChanged(object sender, EventArgs e)
    {
        NewLabel.Visible = true;
    }
}

但是当我尝试执行此操作时,这是我得到的错误 - Control with ID 'up' being registered through RegisterAsyncPostBackControl or RegisterPostBackControl must implement either INamingContainer, IPostBackDataHandler, or IPostBackEventHandler. 请解决我的问题。提前谢谢!

1 个答案:

答案 0 :(得分:0)

如果符合以下条件,它将起作用:

  1. 您不能将创建代码放在if (!IsPostBack)中:必须在每次回发时重新创建动态控件
  2. 您向UpdatePanel添加一个触发PostBack的控件,如Button(如Webruster所述)
  3. 您使用ScriptManager1.RegisterAsyncPostBackControl(btn1)注册该控件,而不是注册UpdatePanel本身