在 vb.net 中填充下拉列表 [英] populating dropdown list in vb.net
问题描述
我有一个从 sql server 数据库填充的下拉列表.填充列表不是问题,但有谁知道如何填充列表项的值部分.
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>
当您从数据库中的表填充时,如何填充 value=1,2,3,4,5?
how do you populate the value=1,2,3,4,5 when you're populating from table in database?
推荐答案
首先你必须构建你的 select 语句
First you have to build your select statement
Select [ID], [Value] From [Table]
您将查询存储到一个变量中(我使用r"作为返回值)然后你需要把它附加到下拉菜单
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
或者使用 DataReader(同样,未经测试,但很快就会关闭)
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
这篇关于在 vb.net 中填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!