back up codes

always have a backup of your code

Archive for the tag “dropdownlist”

enable/disable dropdownlist

The following code will disable the control:


Public Sub disabledddl(ByVal cs As ControlCollection)
Dim d As Control
For Each d In cs
If TypeOf d Is DropDownList Then
CType(d, DropDownList).Enabled = False
End If
disabledddl(d.Controls)
Next
End Sub

The following code will enable the control


Public Sub enabledddl(ByVal cs As ControlCollection)
Dim d As Control
For Each d In cs
If TypeOf d Is DropDownList Then
CType(d, DropDownList).Enabled = True
End If
disabledddl(d.Controls)
Next
End Sub

Then call the sub routine as:


enabledddl(Me.Controls)
disabledddl(Me.Controls)

dynamically adding items to a dropdownlist

There are two ways to add items to a dropdownlist:

a. inserting items extracted from database one at a time

command = New Data.SqlClient.SqlCommand("SELECT * FROM TABLE", connection)
reader = command.ExecuteReader()
Dim items As New ListItem()
Do While reader.Read()
items = New ListItem()
items.Text = reader("TABLE_COLUMN")
items.Value = reader("TABLE_PK")
dropdownlist.Items.Add(items)
Loop
reader.Close()

b. by binding it to a dataset datasource

command = New Data.SqlClient.SqlCommand("SELECT * FROM TABLE", connection)
reader = command.ExecuteReader()
If reader.Read() Then
reader.Close()
adapter.SelectCommand = New Data.SqlClient.SqlCommand("SELECT * FROM TABLE", connection)
adapter.Fill(dataSet)
dropdownlist.DataSource = dataSet.Tables(0)
dropdownlist.DataBind()
End If
reader.Close()

The advantage of the first option is that, a default selected value can be displayed. This can be done with this code:

dropdownlist.Items.Insert(0, "Select")

While on the second option, data retrieved are the ones displayed on the dropdownlist. The first to be extracted is the one displayed as default value.

Both actions would require you to open your connection by:

connection.Open()

And then closing it after using:

connection.Close()

Post Navigation

Follow

Get every new post delivered to your Inbox.