繁体   English   中英

动态控件-清除容器中所有控件的替代方法

[英]Dynamic controls - Alternative to clear all control in the container

我正在使用动态控件进行一些测试。 这里的代码:

ASPX页面

<!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:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem Value="0">Nothing</asp:ListItem>
            <asp:ListItem Value="1">Two buttons</asp:ListItem>
        </asp:DropDownList>
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
    </div>
    </form>
</body>
</html>

后面的代码:

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ViewState["CreateDynamicButton"] != null)
        {
            CreateControls();
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        CreateControls();
    }

    void Button_Click(object sender, EventArgs e)
    {
        Button b = (Button)sender;

        Response.Write("You clicked the button with ID " + b.ID);
    }

    private void CreateControls()
    {
        if (DropDownList1.SelectedValue.Equals("1"))
        {
            Panel1.Controls.Clear();

            Button b1 = new Button();
            b1.ID = "b1";
            b1.Text = "Button 1";

            Button b2 = new Button();
            b2.ID = "b2";
            b2.Text = "Button 2";

            b1.Click += new EventHandler(Button_Click);
            b2.Click += new EventHandler(Button_Click);

            Panel1.Controls.Add(b1);
            Panel1.Controls.Add(b2);

            ViewState["CreateDynamicButton"] = true;
        }
    }
}

这段代码有效,但是如您所见,我删除了Panel1.Controls中的所有控件,然后才添加按钮,因为当我选择第二次创建按钮时,我得到了重复控件ID的实例。

我认为,对于两个按钮,操作速度非常快,但是如果使用更多的控件,则设计时间会更长。 如果没有此解决方法,您能建议我一种在PostBack之后重新生成控件的更好方法吗?

首先,如果您想永久删除控件(在这种情况下为按钮),那么最好使用Dispose方法吗? 清除控件面板不会处理它,这将解释已经在使用的ID。 您可以执行一个简单的循环来执行此操作,而不管面板中有多少控件。

foreach(Control control in Container)
{
  control.Dispose();
}

另外,要创建按钮,我看到您只是将它们命名为btn1,btn2等。 您也可以循环执行此操作;

for(int i = 0; i >= yourInt; i++)
{
  Button b = new Button();
  b.ID = "b" + i;
  b.Text = "Button " + i;
}

}

创建一个类变量private bool ControlsCreated = false; 在您的CreateControls方法中,然后检查

if (!ControlsCreated) {
    //your code to create controls
}

这样可以确保仅创建一次控件。 如果以后在任何时候需要重新创建控件(下拉列表值已更改),只需清除容器并将ControlsCreated设置为false。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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