【问题标题】:Assign Selected item for ComboBox that is filled with custom class为填充有自定义类的 ComboBox 分配选定项
【发布时间】:2017-06-03 12:27:46
【问题描述】:

所以我有一个 ComboBox,它使用自定义类由数据库中的数据填充到 formLoad 上。 这是课程:

  public class ComboBoxItem
    {
        public string Text { get; set; }
        public object Value { get; set; }
        public override string ToString()
        {
            return Text;
        }
    }

我像这样填充组合框:

    foreach (DataRow dr in dt.Rows)
        {
            ComboBoxItem itm = new ComboBoxItem();
            itm.Value = dr["Userid"];
            itm.Text = dr["UserName"].ToString();

            comboCoach.Items.Add(itm);

        }

例如,如果我添加的 ComboBox 项目之一具有“对象值 = 15”。 然后我想将 comboBox.SelectedItem 分配给 value = 15 的 ComboBoxItem。我该怎么做呢?

我确定这是我忽略了的一些简单的事情。

感谢任何帮助。

【问题讨论】:

    标签: c#


    【解决方案1】:

    试试这个:

    var matching = comboCoach.Items.Cast<ComboBoxItem>().FirstOrDefault(z => z.Value == 15);
    
    if (matching != null)
        comboCoach.SelectedItem = matching;
    

    另见Select ComboBox by value in winforms

    【讨论】:

    • 是的,这是我需要的。谢谢你的时间:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多