简体   繁体   English

C#-如何通过比较我的int值在组合框中设置所选项目?

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

I'm using a ComboBox with items having text and value. 我正在使用具有文本和值的项目的ComboBox。 Now, I want to simply make an item selected by comparing its value with the provided value. 现在,我想简单地通过将其值与提供的值进行比较来选择一个项目。 I'm iterating through the items and comparing as follow. 我正在遍历这些项目并进行如下比较。 Below code works fine, but is there a better or more simpler way to do this? 下面的代码工作正常,但是有更好或更简单的方法吗? I found a possible duplicate here but it works with the string value not integer. 我在这里找到了可能的重复项但它与字符串值(不是整数)一起工作。

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

Use display and value memeber 使用显示和价值成员

Create custom class like this: 创建这样的自定义类:

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

now load data you want to display inside List<MyCustomClass>() and then bind that list to combobox and set it's display and value member like this: 现在加载要在List<MyCustomClass>()显示的数据,然后将该列表绑定到组合框并设置其显示和值成员,如下所示:

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

Now simply use myComboBox.SelectedValue = valueYouWant 现在只需使用myComboBox.SelectedValue = valueYouWant

IMPORTANT!!! 重要!!!

Declare displayMember and valueMember before binding datasource to combobox because of perfomance. 由于性能原因,请在将数据源绑定到组合框之前声明displayMember和valueMember。 Search internet for more info. 在互联网上搜索更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM