In this article I will explain with an example, how to add (insert) item in ASP.Net DropDownList using For Loop in C# and VB.Net.
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.
HTML Markup
The HTML Markup consists of an ASP.Net DropDownList which will be populated from database.
<asp:DropDownList ID = "ddlCustomers" runat="server">
</asp:DropDownList>
Namespaces
You will need to import the following namespaces.
C#
using System.Collections;
VB.Net
Imports System.Collections
Adding (Inserting) item in ASP.Net DropDownList using For Loop in C# and VB.Net
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.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ArrayList customers = new ArrayList();
customers.Add("John Hammond");
customers.Add("Mudassar Khan");
customers.Add("Suzanne Mathews");
customers.Add("Robert 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()));
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim customers As New ArrayList()
customers.Add("John Hammond")
customers.Add("Mudassar Khan")
customers.Add("Suzanne Mathews")
customers.Add("Robert Schidner")
'Add blank item at index 0.
ddlCustomers.Items.Insert(0, New ListItem("", ""))
'Loop and add items from ArrayList.
For Each customer As Object In customers
ddlCustomers.Items.Add(New ListItem(customer.ToString(), customer.ToString()))
Next
End If
End Sub
Screenshot
Demo
Downloads