我已经动态创建了5个下拉列表。它来自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 />"));
}
我已经有了另一个下拉代码,比如
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"));}
如何使用此代码动态创建新的5个下拉列表?
答案 0 :(得分:0)
请查看Mysterio11&amp;的评论。取胜。
填写数据的基本思想如下。最重要的是,它没有得到优化。在循环中创建命令和连接是个坏主意。
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"));
}
}