populating dropdown list in vb.net
i have a dropdownlist that populates from the sql server database. populating the list is not a problem, but does anyone know how to populate the value part of the listitem.
<asp:dropdownlist id="colors">
<listitem value="1">black</listitem>
<listitem value="2">blue</listitem>
<listitem value="3">orange</listitem>
<listitem value="4">red</listitem>
<listitem value="5">violet</listitem>
how do开发者_Go百科 you populate the value=1,2,3,4,5 when you're populating from table in database?
First you have to build your select statement
Select [ID], [Value] From [Table]
You would store your query into a variable (I use "r" for return) Then you need to attach it to the dropdown
DropDownList1.DataTextField = r.Value
DropDownList1.DataValueField = r.ID
DropDownList1.Databind()
If you really REALLY need to loop, then try something along these lines (not code is not checked, just a general idea.)
For Each o as object in r
DropDownList1.Items.Insert(o.ID,new ListItem(o.Value,o.ID))
Next
Or with the DataReader (again, untested, but prolly close)
While DataReader.Read()
DropDownList1.Items.Insert(datareader("value"),new ListItem(datareader("name"),datareader("value"))
End While
Assuming that you have an IList implementation which you are binding the data objects to (you seem to have the results materialized in something already, as you say you can populate the text), what you need to do is specify the name of the property/member on your instances returned from your IList implementation.
So, assuming that you have a DataTable with columns of ID and Value, or an IList of objects that was populated from LINQ-to-SQL/Entities, each with an ID property and a Value property, you would do this:
DropDownList1.DataValueField = "ID"
DropDownList1.DataTextField = "Value"
You need to set it to the names of the fields as opposed to the values, as the binding mechanism uses the property descriptor framework to figure out how to map those strings to the properties/columns which contain the data.
精彩评论