加载组合框数据源

时间:2015-04-22 20:20:42

标签: c# combobox datasource

所以我想要使用一个函数来加载组合框的数据源,该函数以字符串形式接收它需要加载的数据源的名称,然后加载它然而我无法使其工作因为我认为该程序只是尝试加载变量名而不是它所代表的数据源。对不起,如果措辞严重,希望我的代码清除我的意思。

这就是我现在正在做的事情

    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。 有谁知道我可以做到这一点的方式?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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);
}