簡體   English   中英

如何識別將選定的ComboBox的項目與一組數據相關的項目?

[英]How do I identify the selected ComboBox's Item relating it to a set of data?

假設我有一組固定的標識符,例如,用字典來組織。

public static Dictionary<int, string> clientIds = new Dictionary<int, string>()
{
    { 0, "aa" },
    { 1, "ab"  },
    { 2, "ac" },
    { 3, "ba" },
    { 4, "bb" }
};

然后,我在運行時動態地將與這些標識符相關的“友好名稱”添加到ComboBox (但是,我不知道將添加哪些標識符)。

clientIdCombo.Add(friendlyName);

假設在索引零處添加了友好名稱“ Alpha Beta”。 那將與“ ab”標識符有關。 我怎么知道用戶已經選擇了“ ab”標識符,而不必以向用戶顯示的組合文本為條件? 我嘗試改用BindingList ,但這也只為我提供了顯示的文本。

聽起來很簡單-如何將基礎數據添加到每個ComboBox索引? 盡管可以采用多種解決方案,但最簡單的方法還是更可取。

謝謝。

ComboBox項可以是您喜歡的任何類型,並且項的顯示名稱將由該類型的ToString方法定義。

這意味着您可以這樣定義商品類型:

class ClientItem
{
    public int Index;
    public string Id;
    public string FriendlyName;
    public override string ToString()
    {
        return FriendlyName;
    }
}

並用此類的實例填充您的組合框。

comboBox.Items.Add(new ClientItem { 
    Index = 1,
    Id = "ab",
    FriendlyName = "Alpha Beta",
});

然后,您可以使用組合框項目訪問所有項目的數據。 只要記住要強制轉換為特定的項目類型:

var client = comboBox.SelectedItem as ClientItem;
MessageBox.Show(client.Id + ": " + client.FriendlyName);

只需向ComboBox中添加與數組中一樣多的項,每一項都具有其對應的文本,並且順序與數組中的順序相同 然后,當您要從數組中獲取所選項目時,請使用ComboBox.SelectedIndex獲取所選索引,並從與該索引對應的數組中獲取該項目。 在您的情況下,您使用的是int-indexed字典,就其索引而言,該字典的行為類似於數組。

TLDR:

string[] array = new[] { "aa", "ab", "ac" };

//This array is "equivalent" to
Dictionary<int, string> dic= new Dictionary<int, string>()
{
    { 0, "aa" },
    { 1, "ab" },
    { 2, "ac" },
};

//Add the items to your ComboBox, for simplicity let's use this
ComboBox.Items.Add("Alfa Alfa");
ComboBox.Items.Add("Alfa Bravo");
ComboBox.Items.Add("Alfa Charlie");

//Later, when retrieving the selected item
int selIndex = ComboBox.SelectedIndex;
string selItem = array[selIndex];

暫無
暫無

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

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