OOP Class12

esse quam videri
Revision as of 17:10, 18 April 2006 by Jeff (talk | contribs) (Dymnically Adding Elements)
Jump to: navigation, search

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>


CheeseArray.aspx - source

<csharp>//an arraylist of cheesew

       Cheese Feta = new Cheese("Feta");
       Cheese Colby = new Cheese("Colby");
       Cheese Gruyere = new Cheese("Gruyere");
       Cheese Edam = new Cheese("Edam");
       
       
       ArrayList alCheeses = new ArrayList();
       alCheeses.Add(Feta);
       alCheeses.Add(Colby);
       alCheeses.Add(Gruyere);
       alCheeses.Add(Edam);</csharp>

and the cheese class <csharp>public class Cheese {

   public string Name;
   public  Milks MilkType;
   public string Region;
   
   public Cheese()
   {
   }
   
   public Cheese(string name)
   {
       this.Name = name;
   }
   
   public enum Milks { Cows, Goats, Mix, Vegetarian }

}</csharp>

Then you can bind the new cheese arraylist to a dropdown box.

CheeseObject.aspx - source

Observer