簡體   English   中英

加載組合框數據源

[英]Loading a combo box data source

所以我想使用一個函數接收一個組合框的數據源,該函數以字符串的形式接收它需要加載的數據源的名稱,然后將其加載,但是我無法像我想的那樣使它工作該程序只是試圖加載變量名,而不是加載它代表的數據源。 抱歉,如果用詞不好,希望我的代碼能清除我的意思。

這就是我現在的做法

    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將是Canada,NZ或RSA。 有人知道我可以這樣做嗎?

制作團隊名稱字典。

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;
}

您可以像這樣制作字典:

dict<string, string[]> teamPlayers;

關鍵是隊名,價值是球員。

team.DataSource = teamPlayers[teamName];

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

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);
}

暫無
暫無

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

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