简体   繁体   English

如何在ASP.NET中动态创建下拉控件

[英]how to operate Dynamically Creating dropdown Controls in ASP.NET

I have created dynamically 5 Dropdown List. 我已经动态创建了5个下拉列表。 It is from aspx.cs 它来自aspx.cs

for (int i = 0; i < 5; i++)
            {
                DropDownList drop = new DropDownList();
                drop.ID = "dropdownlist" + i;
                form1.Controls.Add(drop);
                form1.Controls.Add(new LiteralControl("<br />"));
             }

I already have another dropdown code like 我已经有了另一个下拉代码

if (!this.IsPostBack)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM RejectedProduct"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    DropDownList1.DataSource = cmd.ExecuteReader();
                    DropDownList1.DataTextField = "Name";
                    DropDownList1.DataValueField = "ID";
                    DropDownList1.DataBind();
                    con.Close();
                }
            }
            DropDownList1.Items.Insert(0, new ListItem("Select Item for adding", "0"));}

How I can use this code for dynamically Creating new 5 dropdown each? 如何使用此代码动态创建新的5个下拉列表?

Please check out comments of Mysterio11 & Win. 请查看Mysterio11&Win的评论。

The basic idea of filling data is below. 填充数据的基本思想如下。 Most importantly it's not optimized. 最重要的是,它没有得到优化。 Creating command and connection in a loop is vary bad idea. 在循环中创建命令和连接是个坏主意。

        if (!this.IsPostBack)
        {
            DropDownList DropDownList1;
            for (int i = 0; i < 5; i++)
            {
                DropDownList1 = (DropDownList)FindControl("dropdownlist" + i);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM RejectedProduct"))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        con.Open();
                        DropDownList1.DataSource = cmd.ExecuteReader();
                        DropDownList1.DataTextField = "Name";
                        DropDownList1.DataValueField = "ID";
                        DropDownList1.DataBind();
                        con.Close();
                    }
                }
                DropDownList1.Items.Insert(0, new ListItem("Select Item for adding", "0"));
            }
        }

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

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