簡體   English   中英

以vb.net的形式在兩個組合框中列出所有國家

[英]list all countries in two comboboxes in a form in vb.net

Imports System.Collections.Generic
Imports System.Globalization
Public Sub ListCountries(SourceCombo As System.Windows.Forms.ComboBox)
        ' Iterate the Framework Cultures...
        For Each ci As CultureInfo In CultureInfo.GetCultures(CultureTypes.AllCultures)
            Dim ri As RegionInfo
            Try
                ri = New RegionInfo(ci.Name)
            Catch
                'If a RegionInfo object could not be created don't use the CultureInfo for the country list.
                Continue For
            End Try
            ' Create new country dictionary entry.
            Dim newKeyValuePair As New KeyValuePair(Of String, String)(ri.EnglishName, ri.ThreeLetterISORegionName)
            ' If the country is not already in the countryList add it...
            If Not countryList.ContainsKey(ri.EnglishName) Then
                countryList.Add(newKeyValuePair.Key, newKeyValuePair.Value)
                SourceCombo.Items.Add(ri.EnglishName)
            End If
        Next
        SourceCombo.Sorted = True

    End Sub

我在表單中添加了三個組合框,並在表單加載事件中為每個組合框調用了三次上述功能。 例如:listcountries(ComboBox1)listcountries(ComboBox2)listcountries(ComboBox3)

但是第一個組合框僅列出所有國家,其他兩個為空。 請幫助我如何解決這個問題。

我使用vb.net 12 Ultimate和Windows 7

謝謝

為什么不返回國家列表對象並使用數據源將其綁定到每個組合框?

當countrylist不包含項目時,也會將項目添加到comboxbox,因此需要清除countrylist。 它應該是comboxbox.Items.Contains()

countryList詞典對於您的類是全局的,並且在調用此方法之前在某處初始化。 因此,第一個調用將字典查找為空,並將信息都添加到字典和組合中,但是第二個調用(和第三個調用)發現字典已填充,因此不會向第二(和第三個)組合中添加任何內容

無需在每次調用此方法時重新創建字典,就可以編寫

Dim countryList as SortedDictionary(Of string, String)

Public Sub ListCountries(SourceCombo As System.Windows.Forms.ComboBox)
    If countryList Is Nothing Then
        countryList = BuildCountryList()
    End If
    SourceCombo.DisplayMember = "Key"
    SourceCombo.ValueMember = "Value"
    SourceCombo.DataSource = New BindingSource(countryList, Nothing)
    ' No need to sort anything         
End Sub

Public Function BuildCountryList() As SortedDictionary(Of String, String)
     Dim temp = New SortedDictionary(Of String, String)
     For Each ci As CultureInfo In CultureInfo.GetCultures(CultureTypes.AllCultures)
        Dim ri As RegionInfo
        Try
            ri = New RegionInfo(ci.Name)
        Catch
            'If a RegionInfo object could not be created don't use the CultureInfo for the country list.
            Continue For
        End Try
        ' If the country is not already in the countryList add it...
        If Not temp.ContainsKey(ri.EnglishName) Then
            temp.Add(ri.EnglishName, ri.ThreeLetterISORegionName)
        End If
    Next
    Return temp
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM