【发布时间】:2016-05-02 02:39:13
【问题描述】:
我已经动态创建了 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 个下拉菜单?
【问题讨论】:
-
在 asp.net 中使用动态控件是一个坏主意,因为控件在每次回发时都会被破坏并且必须重新创建。他们不会保持你投入的价值。这样做是个坏主意。
-
动态创建控件只需几个步骤;你错过了很多步骤。看this的回答。如果您有具体问题,请回来再问。