enter image description here I need help about that I have some country names in Combobox
. I want like a first show from (A) then show from (B) like alphabetic order.
Dim connection As New SqlConnection("Data Source=PC1-PC;Initial Catalog=Test2;Integrated Security=True")
Dim command As New SqlCommand("select * from Table_6", connection)
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
ComboBox1.DataSource = table
ComboBox1.DisplayMember = "Country"
Build a list of your countries. Then sort the list and add to combobox.
Private Sub OpCode()
Dim Countries As New List(Of String) From {"Cabo Verde", "Ecuador", "Haiti", "Iraq", "El Salvador", "Djibouti", "France", "Bahrain",
"Cameroon", "Guinea", "Albania", "Finland", "Italy", "Jordan", "Grenada", "Dominica"}
Countries.Sort()
ComboBox1.Items.AddRange(Countries.ToArray)
End Sub
EDIT
OKay, I am calling the field you are interested in "CountryName"
. I am assuming it is the second field in the table which is index 1
.
The Using...End Using
statements ensure that your database objects are closed and disposed even if there is an error. You don't need a DataAdapter
; just load the DataTable
.
The best approach to getting the list sorted is to let the database do the work by adding an Order By
clause.
Private Function GetCountryNames() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection("Data Source=PC1-PC;Initial Catalog=Test2;Integrated Security=True"),
cmd As New SqlCommand("Select * From Tabel_6 Order By CountryName;", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub FillSortedCountriesCombo()
ComboBox1.DataSource = GetCountryNames()
ComboBox1.DisplayMember = "CountryName"
End Sub
If, for some reason, you need to do the sort in code then...
Private Sub FillUnsortedCountriesCombo()
Dim dt = GetCountryNames()
Dim CountriesArray = (From row In dt.AsEnumerable
Order By row.Field(Of String)(1)
Select row("CountryName")).ToArray
ComboBox1.Items.AddRange(CountriesArray)
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.