[英]Add data from database in a drop down in vb.net
I have a drop down list for cities, and I have cities in my database that I want to populate to a drop down list. 我有一个城市的下拉列表,并且我的数据库中有一些城市要填充到一个下拉列表中。
On the Page load made an sql connection 在页面加载上建立了一个sql连接
Dim s As String = "Connection String"
sqlconn = New SqlConnection(s)
Now on the drop down load I have a query which is working fine. 现在,在下拉负载中,我有一个运行良好的查询。 How to add results from the database query to the drop down? 如何将数据库查询的结果添加到下拉列表中?
Protected Sub Citydropdown_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Citydropdown.Load
sqlCmd = New SqlCommand("select City from usrRegister_aunthentication", sqlconn)
If sqlconn.State = Data.ConnectionState.Closed Then
sqlconn.Open()
End If
Dim i As String = sqlCmd.ExecuteReader()
If sqlconn.State = Data.ConnectionState.Open Then
sqlconn.Close()
End If
End Sub
Also, sometimes the same city is repeated. 此外,有时会重复同一座城市。 How do I only show each city once? 我如何只显示每个城市一次?
Do not use ExecuteNonQuery
to fetch the result (rows). 不要使用ExecuteNonQuery
来获取结果(行)。 Use ExecuteReader
to obtains the reader instance. 使用ExecuteReader
获取阅读器实例。
Dim dataReader as SqlDataReader
dataReader = sqlCmd.ExecuteReader()
While dataReader.Read
' Write code to insert an Item into dropdownlist
DropDownItem1.Items.Add(dataReader("City").ToString())
End While
dataReader.Close()
You could also try this. 您也可以尝试一下。 It is a line or two less. 少一两行。
Using dr = sqlCmd.ExecuteReader()
While dr.Read
' Write code to insert an Item into dropdownlist
DropDownItem1.Items.Add(dr("City").ToString())
End While
End Using
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.