Add item in ASP.Net DropDownList using For Loop

how Add item in ASP.Net DropDownList using For Loop in C#?



A For Loop will be executed over an ArrayList (Array) and one by one each item of the ArrayList will be added to the ASP.Net DropDownList.


<asp:DropDownList ID = "ddlCustomers" runat="server">
</asp:DropDownList>




in Behind Code



using System.Collections;
 
Inside the Page Load event of the page, an ArrayList (Array) is populated with the some string values of Customer names.
First a blank (empty) item is inserted at the first position and then a loop is executed over the ArrayList items and one by one each item is added to the DropDownList.
 
 
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ArrayList customers = new ArrayList();
  customers.Add("John");
  customers.Add("Khan");
  customers.Add("Mathews");
  customers.Add("Schidner");

//Add blank item at index 0.
ddlCustomers.Items.Insert(0, new ListItem("", ""));

//Loop and add items from ArrayList.
foreach (object customer in customers)
{
ddlCustomers.Items.Add(new ListItem(customer.ToString(), customer.ToString()));
}
}
}

No comments:

Post a Comment