如何在ComboBox中过滤数据Vb.Net

时间:2019-12-11 06:53:47

标签: sql-server vb.net

enter image description here我需要帮助,因为我在Combobox中有一些国家/地区名称。我想像(A)中的第一个节目,然后像字母顺序那样从(B)中显示。

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"

enter image description here

1 个答案:

答案 0 :(得分:0)

建立您的国家清单。然后对列表进行排序并添加到组合框。

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

编辑

好的,我正在致电您对"CountryName"感兴趣的字段。我假设它是表中索引为1的第二个字段。

Using...End Using语句可确保即使有错误,也可以关闭和处置数据库对象。您不需要DataAdapter;只需加载DataTable

对列表进行排序的最佳方法是让数据库通过添加Order By子句来完成工作。

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

如果由于某种原因需要在代码中进行排序,那么...

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