Dropdownlist anyone ???

  • Thread starter Thread starter Hai Nguyen
  • Start date Start date
H

Hai Nguyen

Hi everyone

I'm developing an wep application, I got stuck into a problem.
My database has a table which has 2 fields
Table1

X Y
A Apple
B Banana
C Cat
D Dog

I would like to ask if there is a way so that I can add these two columns
into my dropdown list which will look like this

Apple
Banna
Cat
Dog

whichever values I select from the dropdownlist I wold like to get the
equivalent value; for instance
if I choose Cat, I want to get the value C for later use.

Thanks for any help
 
You just need to tell the DataTextField and DataValueField properties the
name or index of the column from the dataset. The dropdownlist will display
one and return the other. Here's some code:


Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
If Not IsPostBack Then
Dim ds As New DataSet
ds = CreateDataset()
DropDownList1.DataSource = ds.Tables(0)
DropDownList1.DataTextField = "Item_name"
DropDownList1.DataValueField = "Item_value"
DropDownList1.DataBind()
End If
End Sub
Private Sub Button1_Click _
(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Label1.Text = DropDownList1.SelectedValue
End Sub
Function CreateDataset() As DataSet
Dim ds As New DataSet
Dim dt As New DataTable
Dim dr As DataRow
dt.Columns.Add(New DataColumn _
("Item_value", GetType(String)))
dt.Columns.Add(New DataColumn _
("Item_name", GetType(String)))
dr = dt.NewRow
dr(0) = "Y"
dr(1) = "X"
dt.Rows.Add(dr)
dr = dt.NewRow
dr(0) = "A"
dr(1) = "Apple"
dt.Rows.Add(dr)
dr = dt.NewRow
dr(0) = "B"
dr(1) = "Banana"
dt.Rows.Add(dr)
dr = dt.NewRow
dr(0) = "C"
dr(1) = "Cat"
dt.Rows.Add(dr)
dr = dt.NewRow
dr(0) = "D"
dr(1) = "Dog"
dt.Rows.Add(dr)
ds.Tables.Add(dt)
Return ds
End Function
 
Back
Top