簡體   English   中英

C#-如何通過比較我的int值在組合框中設置所選項目?

[英]C# - How do I set the selected item in a combobox by comparing my int value?

我正在使用具有文本和值的項目的ComboBox。 現在,我想簡單地通過將其值與提供的值進行比較來選擇一個項目。 我正在遍歷這些項目並進行如下比較。 下面的代碼工作正常,但是有更好或更簡單的方法嗎? 我在這里找到了可能的重復項但它與字符串值(不是整數)一起工作。

foreach (ComboboxItem item in this.CampaignList.Items)
{
    if (Convert.ToInt16(item.Value) == objAACampaign.CompanyId)
    {
        this.CampaignList.SelectedIndex = this.CampaignList.Items.IndexOf(item);
        break;
    }
}

使用顯示和價值成員

創建這樣的自定義類:

class MyCustomClass
{
    //important to have get set part
    public _int { get; set; }
    public _string { get; set; }
}

現在加載要在List<MyCustomClass>()顯示的數據,然后將該列表綁定到組合框並設置其顯示和值成員,如下所示:

myComboBox.DisplayMember = "_string";
myComboBox.ValueMember = "_int";
myComboBox.DataSource = myList; //this is List<MyCustomClass>

現在只需使用myComboBox.SelectedValue = valueYouWant

重要!!!

由於性能原因,請在將數據源綁定到組合框之前聲明displayMember和valueMember。 在互聯網上搜索更多信息。

暫無
暫無

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

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