动态下拉列表消失

时间:2014-06-18 12:14:05

标签: c# asp.net

我从数据库中填充动态添加的下拉列表。当我按下asp.net表单上的按钮时,动态添加的下拉列表会重新填充。 如果我检查ispostback并阻止创建代码,则ddls不会显示。阻止每个帖子构建ddls的最佳方法是什么。

public partial class search : System.Web.UI.Page
{
    Panel SearchPanel;
    protected void Page_PreInit(object sender, EventArgs e)
    {
        //Create a Dynamic Panel
        SearchPanel = new Panel();
        SearchPanel.ID = "SearchPanel";
        SearchPanel.BorderWidth = 1;
        SearchPanel.Width = 300;
        this.form1.Controls.Add(SearchPanel);

        CreateDropDownList("search1");
        CreateDropDownList("search2");

        Button btnAddDd2 = new Button();
        btnAddDd2.ID = "btnAddDd2";
        btnAddDd2.Text = "Search";
        btnAddDd2.Width = 80;
        btnAddDd2.Click += new System.EventHandler(search_click);
        this.form1.Controls.Add(btnAddDd2);

    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void CreateDropDownList(string ID)
    {
        DropDownList ddl = new DropDownList();
        ddl.ID = ID;
        ddl.Items.Add(new ListItem("--Select--", ""));
        ddl.Items.Add(new ListItem("One", "1"));
        ddl.Items.Add(new ListItem("Two", "2"));
        ddl.Items.Add(new ListItem("Three", "3"));
        ddl.AutoPostBack = true;

        SearchPanel.Controls.Add(ddl);

        Literal lt = new Literal();
        lt.Text = "<br />";
        SearchPanel.Controls.Add(lt);

        Thread.Sleep(2000); // simulate wait time of database load
    }

    protected void search_click(object sender, EventArgs e)
    {
        // find something
    }
}

1 个答案:

答案 0 :(得分:0)

动态创建的控件在触发回发事件时丢失了它们的值。此外,如果您检查IsPostback然后在回发事件上,您将失去动态控件。要解决此问题,您需要使用ViewState属性。

有关详细说明和示例,请点击以下链接:Retaining State for Dynamically Created Controls in ASP.NET applications