Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add items to dropdownlist

Status
Not open for further replies.

Kai77

Programmer
Jun 7, 2004
77
NL
I want to add items (text/value pair) to a dropdownlist. How come I only get items which are all the same (all items have the same text/value as the last item that is being added)?

My code:

Dim ddlItem As New ListItem
ddlItem.Text = "April 2005"
ddlItem.Value = "April"
ddlMonthYear.Items.Add(ddlItem)

ddlItem.Text = "Mei 2005"
ddlItem.Value = "May"
ddlMonthYear.Items.Add(ddlItem)

ddlItem.Text = "Juni 2005"
ddlItem.Value = "June"
ddlMonthYear.Items.Add(ddlItem)

ddlItem.Text = "Juli 2005"
ddlItem.Value = "July"
ddlMonthYear.Items.Add(ddlItem)

ddlItem.Text = "Augustus 2005"
ddlItem.Value = "August"
ddlMonthYear.Items.Add(ddlItem)
 
well i think it's because you add ddlitem many times but it's always the same object, you only change its values each time.


try

Code:
Dim ddlItem1 As New ListItem
ddlItem1.Text = "April 2005"
ddlItem1.Value = "April"
ddlMonthYear.Items.Add(ddlItem1)

Dim ddlItem2 As New ListItem
ddlItem2.Text = "Mei 2005"
ddlItem2.Value = "May"
ddlMonthYear.Items.Add(ddlItem2)

Dim ddlItem3 As New ListItem
ddlItem3.Text = "Juni 2005"
ddlItem3.Value = "June"
ddlMonthYear.Items.Add(ddlItem3)

Dim ddlItem4 As New ListItem
ddlItem4.Text = "Juli 2005"
ddlItem4.Value = "July"
ddlMonthYear.Items.Add(ddlItem4)

Dim ddlItem5 As New ListItem
ddlItem5.Text = "Augustus 2005"
ddlItem5.Value = "August"
ddlMonthYear.Items.Add(ddlItem5)


 
it works, but isnt there a more efficient way to do this, where i do not have to declare a new listitem?
 
well you can loop on records received from a database.

imagine you have a datatable dt:


Code:
For each dr As datarow in dt
dim dllItem as New ListItem
ddlItem.Text = dr(nameOfFieldAsString)'instead of a string you can put the column index as integer
ddlItem.Value = dr(nameOfOtherFieldAsString)'instead of a string you can put the column index as integer
ddlMonthYear.Items.Add(ddlItem)
Next
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top