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终极版& Windows 7
谢谢
答案 0 :(得分:0)
为什么不返回国家/地区列表对象并使用数据源绑定到每个组合框?
当countrylist不包含时,也会将项目添加到comboxbox,因此需要清除国家/地区列表。它应该是comboxbox.Items.Contains()
答案 1 :(得分:0)
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