在 vb.net 中填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2346381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
populating dropdown list in vb.net
提问by ugio
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.
我有一个从 sql server 数据库填充的下拉列表。填充列表不是问题,但有谁知道如何填充列表项的值部分。
<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 you populate the value=1,2,3,4,5 when you're populating from table in database?
当您从数据库中的表填充时,如何填充 value=1,2,3,4,5?
采纳答案by Chase Florell
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
您将您的查询存储到一个变量中(我使用“r”返回)然后您需要将其附加到下拉列表中
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)
或者使用 DataReader(同样,未经测试,但很快就会关闭)
While DataReader.Read()
DropDownList1.Items.Insert(datareader("value"),new ListItem(datareader("name"),datareader("value"))
End While
回答by casperOne
Assuming that you have an IList implementation which you are binding the data objects to (you seem to have the results materialized in somethingalready, as you say you can populate the text), what you need to do is specify the nameof the property/member on your instances returned from your IList implementation.
假设你有一个IList实现你所绑定的数据对象(你似乎有结果的物化的东西已经像你说的,你可以填充文本),你需要做的是指定什么名称的属性/从您的 IList 实现返回的实例上的成员。
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:
因此,假设您有一个包含 ID 和 Value 列的 DataTable,或者一个从 LINQ-to-SQL/Entities 填充的对象 IList,每个对象都有一个 ID 属性和一个 Value 属性,您可以这样做:
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.
您需要将其设置为字段的名称而不是值,因为绑定机制使用属性描述符框架来确定如何将这些字符串映射到包含数据的属性/列。