Dynamically build dropdownlist box

D

DaveF

When I select the first dropdownlist box, I need to be able to make several
dropdownlist boxes on the fly and populate them from the database. Is this
possible? If so, HOW?
 
K

Ken Cox [Microsoft MVP]

Hi Dave,

The easiest way is to add a PlaceHolder control to your page. Then, create
the dropdownlist on the fly, add the items to the ddl from the database and
finally add the ddl to the PlaceHolder. Here's the idea:

Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
'Put user code to initialize the page here
End Sub

Private Sub DropDownList1_SelectedIndexChanged _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles DropDownList1.SelectedIndexChanged
Dim ddlData As New DropDownList
Dim dt As DataTable
Dim lstItem As ListItem
Dim dr As DataRow
dt = CreateDataSource()
For Each dr In dt.Rows
lstItem = New ListItem
lstItem.Text = dr.Item("StringValue")
lstItem.Value = dr.Item("IntegerValue")
ddlData.Items.Add(lstItem)
Next
PlaceHolder1.Controls.Add(ddlData)
End Sub

Function CreateDataSource() As DataTable
Dim dt As New DataTable
Dim dr As DataRow
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
dt.Columns.Add(New DataColumn("Boolean", GetType(Boolean)))
Dim i As Integer
For i = 0 To 8
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " + i.ToString()
dr(2) = 1.23 * (i + 1)
dr(3) = (i = 4)
dt.Rows.Add(dr)
Next i
Return dt
End Function 'CreateDataSource

<form id="Form1" method="post" runat="server">
<P>
<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True">
<asp:ListItem Value="--Select--">--Select--</asp:ListItem>
<asp:ListItem Value="Items">Items</asp:ListItem>
<asp:ListItem Value="Colours">Colours</asp:ListItem>
</asp:DropDownList></P>
<P>
<asp:placeHolder id="PlaceHolder1" runat="server"></asp:placeHolder></P>
</form>

Does this help?

Ken
Microsoft MVP [ASP.NET]
Toronto
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top