I\'m trying to add an array of controls to an aspx page (C# code behind). These are the similar controls (search criteria for separate fields but will have the same values)
Control.FindControl is what you're looking for. You can use it on any Control(like Page itself) to find controls via their NamingContainer. Put them e.g. in a Panel and use FindControl on it.
for (int x = 0; x < 20; x++) {
DropDownList ddlFruit = (DropDownList)FruitPanel.FindControl("FruitDropDown" + x);
ddlFruit.Items.AddRange(items[x]);
}
You can also create them dynamically:
for (int x = 0; x < 20; x++) {
DropDownList ddlFruit = new DropDownList();
ddlFruit.ID = "FruitDropDown" + x
ddlFruit.Items.AddRange(items[x]);
FruitPanel.Controls.Add(ddlFruit);
}
You must recreate dynamically created controls on every postback at the latest in Page_Load with the same ID as before to ensure that ViewState is loaded correctly and events are triggered.