i want to add some data into dropdownlist from database and don't have duplicate data , so i did this ~
Dim ads As New Web.UI.WebControls.AccessDataSource
ads.DataFile = "~/app_data/board.mdb"
ads.SelectCommand = "SELECT DISTINCT [photo_species] FROM [phototable]"
Dim dv As DataView = ads.Select(New DataSourceSelectArguments)
For i = 0 To dv.Count - 1
DropDownList1.Items.Add(dv.Item(0).Row("photo_species"))
Next
but when i run the code it shows the same data again and again
CodePudding user response:
Change the 0 in this line:
DropDownList1.Items.Add(dv.Item(0).Row("photo_species"))
to i:
DropDownList1.Items.Add(dv.Item(i).Row("photo_species"))
CodePudding user response:
It is not clear if this is a vb.net (NOT vb6), and it not clear if this is a web page (asp.net), or a desktop only program?
If this is asp.net (web based), then this should work:
First, the web markup is this:
<h3>Select Hotel</h3>
<asp:DropDownList ID="DropDownList1" runat="server"
DataValueField="ID"
DataTextField="HotelName" height="30px" Width="206px">
</asp:DropDownList>
Like most drop downs, there are (can be) two columns.
The "hidden" value - in most cases the database PK row ID.
And then the display value. (hence in above Value field, and text field).
DataValueField = hidden column - value returned from drop down DataTextField = the display column from the data table (to display).
our code to load is thus this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
End Sub
Sub LoadData()
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL =
"SELECT ID, Hotelname FROM tblhotelsA ORDER BY HotelName"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
DropDownList1.DataSource = rstData
DropDownList1.DataBind()
' add default please select
DropDownList1.Items.Insert(0, New ListItem("Please Select Hotel", ""))
End Using
End Using
End Sub
And we now get this:
And if in code we need to test/get/look at/grab the selected value?
Then use this code:
Debug.Print("drop down pk (id) = " & DropDownList1.SelectedItem.Value)
Debug.Print("drop down hotel text = " & DropDownList1.SelectedItem.Text)
The above allows you to get both columns (the hidden one), and the text/display one.
As a general rule, you can also use the .Text property of the drop down list to get the selected value.
So, this also gets the value.
Debug.Print("drop down value = " & DropDownList1.Text)
so, above will return the same as DropDownList1.SelectedItem.Value