The .aspx file has it’s usual html code and a “Panel1” control in it.
First of all i’m creating a dropdownlist called “ddl” and add to it some ListItems, all this from the code behind. Next i want to create a certain number of other DropDownLists and copy to them all the ListItems I added to the “ddl”, after that i need them to be added to a “Panel1” control when the page is running. The most important part is that I want all the dynamically created dropdownlists to have a selected value when running the page. You can see the code below:
protected void Page_Load(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
ddl.Items.Add(new ListItem("One", "1"));
ddl.Items.Add(new ListItem("Two", "2"));
ddl.Items.Add(new ListItem("Three", "3"));
ddl.Items.Add(new ListItem("Four", "4"));
ddl.Items.Add(new ListItem("Five", "5"));
ddl.Items.Add(new ListItem("Six", "6"));
ddl.Items.Add(new ListItem("Seven", "7"));
int j = 2;
for (int h = 0; h < 3; h++)
{
DropDownList ddlDynamic = new DropDownList();
//Add the items from ddl to the new dropdownlsit
for (int i = 0; i < ddl.Items.Count; i++)
{
ddlDynamic.Items.Add(ddl.Items[i]);
}
//the selected item in the first dropdownlist
//must be "Two" but it will be "Four". WHY???
ddlDynamic.SelectedValue = j.ToString();
ddlDynamic.ID = h.ToString();
Panel1.Controls.Add(ddlDynamic);
Panel1.Controls.Add(new LiteralControl("<br />"));
j++;
}
}
The problem here is that the selected value for all three dropdownlists will be the same and it will be “Four”, when logically the first must be “Two”, second “Three” and the third must has “Four” as selected value. First question is: What am I doing wrong?
Second question.
When using ddlDynamic.Items.FindByValue(j.ToString()).Selected = true; instead of ddlDynamic.SelectedValue = j.ToString(); I am getting a “Cannot have multiple items selected in a DropDownList.” Why is that?
Thank You.
I found the answer. The important thing here is to remember that
ddlDynamic.Items.Add(ddl.Items[i]);line, adds the items by reference from the “ddl” dropdownlist, and does not copy the ListItems into each DropDownLists created dynamically with the “for” loop. All the dropdownlists created dynamically are using THE SAME ListItems initialized before and added to the “ddl”. It’s important to know that:will do the same thing: will use the ListItems by reference from the “ddl”. So the solution i found is to create ListItems for each dynamically created DropDownList, and populate them from a source, in that case it will be a DataTable:
If someone has a better idea, please let me know.