vb.net 使用 SQL 填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26513434/
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
Populate a Dropdown list With SQL
提问by Nils
i have a DropDownList in my asp.net website but i can not get it to populate with data from my sql server.
我在我的 asp.net 网站中有一个 DropDownList,但我无法使用我的 sql 服务器中的数据填充它。
am i missing something?
我错过了什么吗?
Dim sqlconn As New SqlConnection
Dim sqCmd As New SqlCommand
Dim sqlreader As SqlDataReader
sqlconn.ConnectionString = "server = .......;Database=......;User ID=....
Password=...."
sqCmd.Connection = sqlconn
sqlconn.Open()
sqCmd.CommandText = "SELECT DISTINCT CompanyDivision FROM Reports"
sqlreader = sqCmd.ExecuteReader()
DropDownList.DataSource = sqlreader
DropDownList.DataTextField = "CompanyDivision"
DropDownList.DataValueField = "CompanyDivision"
DropDownList.DataBind()
sqlreader.Close()
sqlconn.Close()
回答by julealgon
The most straightforward way of attaching a sql query to a dropdown is through the use of a SqlDataSourcein the aspx.
将 sql 查询附加到下拉列表的最直接方法是通过SqlDataSource在 aspx 中使用 a 。
You can do it like this:
你可以这样做:
<asp:SqlDataSource runat="server"
ID="CompanyDivisionSource"
DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:YourConnectionStringKey%>"
SelectCommand="SELECT DISTINCT CompanyDivision FROM Reports" />
<asp:DropDownList runat="server"
DataSourceID="CompanyDivisionSource"
DataTextField="CompanyDivision"
DataValueField="CompanyDivision" />
I recommend the use of that expression for the connection string also. You need to place your connection string on the web.config file, under the <connectionStrings>tag. You will them be able to reuse the same connection across many pages without having to hardcode it on every use.
我也建议对连接字符串使用该表达式。您需要将连接字符串放在 web.config 文件的<connectionStrings>标记下。您将能够在多个页面上重复使用相同的连接,而无需在每次使用时对其进行硬编码。
More about the SqlDataSourcecan be found on this overview.
更多关于SqlDataSource上可以找到此概述。

