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