DropdownList and DataValue

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
 
J

January Smith

Dim liItem As New ListItem

liItem.Value = 1

liItem.Text = "IN"

DropDown1.Items.Add(liItem)



Regards,

January Smith
 
S

Steven Cheng[MSFT]

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
 
A

A.M

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
 
S

Steven Cheng[MSFT]

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
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top