Items can be added dynamically to a VB DropDownList, from the code behind page as well as statically in front end html .ascx page.
Illustrated below is the HTML version of a DropDownlist, together with 3 entries for Daily, Weekly and Monthly.
<asp:DropdownList id="ddlFrequency" runat="server"> <asp:ListItem Text="Daily" Value="Daily" Selected="True"></asp:ListItem> <asp:ListItem Text="Weekly" Value="Weekly"></asp:ListItem> <asp:ListItem Text="Monthly" Value="Monthly"></asp:ListItem> </asp:DropdownList>
In the code behind to add an extra item, the following code is added:
ddlFrequency.Items.Add(“Yearly”)
To add a value/text pair, the following is used:
ddlYear.Items.Add(New ListItem(“1992”, “(J/K)”))
To make use of the ListItem it is necessary to add
Imports System.Web.UI.WebControls
at the start of your code.
To add the items from a collection:
'Clear the dropdownlist entries
'prevents possible duplication
ddlApplPrefix.Items.Clear()
Dim lc As ListController = New ListController()
Dim leic As ListEntryInfoCollection = lc.GetListEntryInfoCollection("HowHear")
ddlApplPrefix.DataTextField = "Text"
ddlApplPrefix.DataValueField = "EntryId"
ddlApplPrefix.DataSource = leic
ddlApplPrefix.DataBind()
In the above example the existing entries assigned to the dropdown list ddlApplPrefix are deleted, before the addition of the entries, thus avoiding duplication, should the function have been called before.
Below is shown the function to add defined entries to the dropdown list.
Private Sub PopulateApplPrefix(ByVal SelectedValue As String)
Try
ddlApplPrefix.Items.Clear()
ddlApplPrefix.Items.Add(New ListItem("Mr"))
ddlApplPrefix.Items.Add(New ListItem("Mrs"))
ddlApplPrefix.Items.Add(New ListItem("Ms"))
ddlApplPrefix.Items.Add(New ListItem("Miss"))
dlApplPrefix.Items.Add(New ListItem("Dr"))
dlApplPrefix.Items.Add(New ListItem("Prof"))
Dim litem As ListItem
For Each litem In ddlApplPrefix.Items
If litem.Value = SelectedValue Then
litem.Selected = True
End If 'litem.Text = NumSelected
Next 'Each litem In ddlApplPrefix.Items
Catch exc As Exception 'Module failed to load
ProcessModuleLoadException(Me, exc)
End Try
End Sub
The function takes a parameter, the value to be set as the selected item.
As before the dropdown list is reset, allowing entries to be added without duplication.
The individual items are added to the list.
The entries in the list are looped through and checked against the selected item passed into the function. when a match is made the Selected property of the entry is set to True.
The catch exception included is relevant to DotNetNuke websites.


