OOP Class12
esse quam videri
Dymnically Adding Elements
Say we have an empty drop down list.
<asp:DropDownList id="ddlCheese" autopostback="True" runat="server" />
Since we know that all Lists in the framework contain ListItems we can dymaically add a bunch of cheeses by using a for loop that creates and add ListItems.
ListItem has several constuctors
Visibility | Constructor | Parameters |
public | ListItem | ( ) |
public | ListItem | ( String text ) |
public | ListItem | ( String text , String value ) |
public | ListItem | ( String text , String value , Boolean enabled ) |
<csharp>
//an array of names of cheese string [] aryNames = new string[5]; aryNames [0] = "Feta"; aryNames [1] = "Colby"; aryNames [2] = "Gruyere"; aryNames [3] = "Edam"; aryNames [4] = "Colby";
foreach (string cheeseName in aryNames) { ListItem newItem = new ListItem(cheeseName, cheeseName); //get a new list item //with i for string text and i for value ddlCheese.Items.Add(newItem); }</csharp>