I have created dynamically 5 Dropdown List. It is from 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?
Please check out comments of 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"));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.