【问题标题】:Select ComboBox by value in winforms在winforms中按值选择ComboBox
【发布时间】:2013-11-20 19:02:08
【问题描述】:

如何在 WinForms 中按值选择组合框?我正在设置这样的组合框:

ComboboxItem item = new ComboboxItem();
                item.Text = "Test";
                item.Value = 1;

cmbComboBox.Items.Add(item);

internal class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

我需要选择 Value = 1 的位置

【问题讨论】:

    标签: c# .net winforms combobox


    【解决方案1】:

    因为ObjectCollection 没有实现通用的IEnumerable<T> 只有IEnumerable,所以您不能使用LINQ 标准查询运算符。但是,只需通过使用Cast<T> 来获得一个 LINQ 友好的可查询集合来作弊:

    var result = comboBox1.Items.Cast<ComboBoxItem>().Where(i => (int.Parse(i.Value.ToString())) == 1);

    【讨论】:

    • 您必须将i.Value 转换为(int),然后在返回ComboboxItem(或null)的查询上调用FirstOrDefault()。一旦你得到它,你就可以在 Items 集合中确定它的索引,这样你就可以设置 SelectedIndex()。
    • True...我假设“选择”他的意思是使 ComboboxItem 成为 ComboBox 中的选定项。如果是这种情况,我想您也可以将 SelectedItem() 设置为返回值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2018-12-06
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多