2016-01-20 39 views
0
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的形式列出兩個組合框中的所有國家

但第一組合框只列出所有國家和其他兩個是空的。請幫我解決這個問題。

IM使用vb.net 12終極& Windows 7的

謝謝

+0

嗯,你知道這個代碼的工作,因爲它知道如何填充至少一個組合框。我們無法看到無法使用的代碼。在輸出窗口中查找「第一次機會異常」通知。注意[這個令人討厭的Windows 7 bug](http://stackoverflow.com/a/4934010/17034)。 –

+0

你有一個全局字典實例,第二個調用被跳過,因爲字典已被前一個調用填充。但跳過添加到詞典中,您也跳過組合框中的插入。 – Steve

+0

任何替代方法? –

回答

0

爲什麼不返回國家列表對象並綁定到數據源使用組合框每一個?

此外,項目被添加到comboxbox當農民不包含那麼需要清除countrylist。它應該是comboxbox.Items.Contains()

+0

我應該在哪一行插入這段代碼? –

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 
+0

當我用代碼運行表單時,所有組合框中都會出現一個字符串「(Collections)」。沒有添加任何項目。它是空的。 –

+0

這很奇怪。我測試了代碼,它的工作原理如下。你能展示你如何稱此代碼? – Steve

+0

Listcountries(ComboBox1) –

相關問題