2015-04-22 77 views
0

所以我想加載一個組合框的數據源與使用一個函數接收作爲一個字符串的數據源的名稱,它需要加載,然後讓它加載它然而我無法得到這個工作,因爲我認爲該程序只是試圖加載變量名稱,而不是它所代表的數據源。對不起,如果這是措辭不良,希望我的代碼清除我的意思。加載組合框數據源

這是我過得怎麼樣,現在

bool TeamPlayers(string teamName, ComboBox team)//Makes the players of the selected team available for selection as scorers 
    { 
     if (teamName == "Canada") 
     { 
      string[] players = {"Johny Moonlight", "DTH Van Der Merwe", "Phil Mackenzie" }; 
      team.DataSource = players; 
     } 
     else if (teamName == "New Zealand") 
     { 
      string[] players = {"Dan Carter", "Richie Mccaw", "Julian Savea" }; 
      team.DataSource = players; 
     } 
     else if (teamName == "South Africa") 
     { 
      string[] players = {"Jean de Villiers", "Bryan Habana", "Morne Steyn" }; 
      team.DataSource = players; 
     } 
     return (true); 
    } 

但是我希望做更多的東西像這樣

bool TeamPlayers(string teamName, ComboBox team)//Makes the players of the selected team available for selection as scorers 
    { 
     string[] Canada = {"Johny Moonlight", "DTH Van Der Merwe", "Phil Mackenzie" }; 
     string[] NZ = {"Dan Carter", "Richie Mccaw", "Julian Savea" }; 
     string[] RSA = {"Jean de Villiers", "Bryan Habana", "Morne Steyn" }; 
     team.DataSource = teamName; 
     return (true); 
    } 

凡teamName將是要麼加拿大,新西蘭或RSA。 有誰知道我可以做到這一點的方式?

回答

0

您可以使用字典來實現類似的功能

bool TeamPlayers(string teamName, ComboBox team)//Makes the players of the selected team available for selection as scorers 
{ 
    Dictionary<string, string[]> teamNames = new Dictionary<string, string[]>(); 

    teamNames.Add("Canada", new string[] { "Johny Moonlight", "DTH Van Der Merwe", "Phil Mackenzie" }); 
    teamNames.Add("New Zealand", new string[] { "Dan Carter", "Richie Mccaw", "Julian Savea" }); 
    teamNames.Add("South Africa", new string[] { "Jean de Villiers", "Bryan Habana", "Morne Steyn" }); 

    team.DataSource = teamNames[teamName]; 
    return (true); 
} 
+0

感謝的是解決我的問題。我能用相機盒做同樣的事嗎? –

+0

@JulienPowell是的,你可以 –

+0

對不起,但你可以澄清一點,因爲我很難做到這一點 –

0

你可以做一本字典,像這樣:

dict<string, string[]> teamPlayers; 

主要是teamname,價值將是玩家。

team.DataSource = teamPlayers[teamName]; 
1

讓球隊的名字的字典。

Dictionary<string, string[]> teams = new Dictionary<string, string[]>(); 

public void PopulateTeams() 
{ 
    teams.Add("canada", new[] { "Johny Moonlight", "DTH Van Der Merwe", "Phil Mackenzie" }); 
    teams.Add("nz", new[] { "Dan Carter", "Richie Mccaw", "Julian Savea" }); 
    teams.Add("rsa", new[] { "Jean de Villiers", "Bryan Habana", "Morne Steyn" }); 
} 

詞典的使用方法:

private bool TeamPlayers(string teamName, ComboBox team) 
{ 
    team.DataSource = null; 
    if (teams.ContainsKey(teamName)) 
    { 
     team.DataSource = teams[teamName]; 
     return true; 
    } 
    return false; 
} 
+0

感謝您的幫助=) –