DropdownList and DataValue

  • Thread starter Thread starter A.M
  • Start date Start date
A

A.M

Hi,

I use following code on PageLoad to supply DataText for a drop down list
box:

Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then

Dim values as ArrayList= new ArrayList()

values.Add ("IN")
values.Add ("KS")
values.Add ("MD")
values.Add ("MI")
values.Add ("OR")
values.Add ("TN")

DropDown1.DataSource = values
DropDown1.DataBind
End If
End Sub

How can I change above code to spply both text and value to a listbox?

Thanks,
Ali
 
Dim liItem As New ListItem

liItem.Value = 1

liItem.Text = "IN"

DropDown1.Items.Add(liItem)



Regards,

January Smith
 
Hi Allan,

I agree with January's suggestion on using the ListItem as the DataSource
member, in addition to directory add ListItem object into the
DropDownList's Items collection, we can also use the DataBind mode to fill
the dropdownlist as below:

Dim items As New ListItemCollection

Dim i As Int32

For i = 1 To 10

Dim item As New ListItem
item.Text = "Text" + i.ToString()
item.Value = "Value" + i.ToString()

items.Add(item)
Next

lstMain.DataSource = items
lstMain.DataTextField = "Text"
lstMain.DataValueField = "Value"
lstMain.DataBind()

#lstMain is a DropDownList

Hope also helps. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
Sorry to reply a little late, But you created 10 ListItems (one in each
iteration)
Wouldn't it be more efficient to create just one ListItem, assign/change the
values and add it into listbox?

Thanks,
Alan
 
Hi Alan,

I'm sorry to forget mention that the "create once I mean" is to declare the
the ListItem Reference once, and we still need to create multi-instance of
the ListItem when we need to add multi items into the DropDownList or other
such collection. Just like:

Dim i As Int32
Dim item As ListItem

For i = 1 To 10

item = New ListItem

item.Text = "Text" + i.ToString()
item.Value = "Value" + i.ToString()

items.Add(item)
Next

Otherwise, all the items will be all the same instances. Thanks.


Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx
 
Back
Top