【问题标题】:How do I Set a combobox with text/index items to a specific item如何将带有文本/索引项的组合框设置为特定项
【发布时间】:2016-12-13 12:44:32
【问题描述】:

据我所知,Windows 窗体中的组合框只能保存一个值。我需要一个文本和一个索引,所以我创建了这个小类:

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

我将一个项目添加到组合框中,如下所示:

ComboboxItem item = new ComboboxItem()
{
    Text = select.Item1,
    Value = select.Item2
};

this.comboBoxSelektion.Items.Add(item);

现在我的问题是:如何将组合框设置为特定项目? 我试过了,但是没有用:

this.comboBoxSelektion.SelectedItem = new ComboboxItem() { Text = "Text", Value = 1};

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    您提供的最后一个代码示例不起作用,因为ComboBox 中的项目和您通过new 创建的项目是不同的实例(= 内存引用),它们不相同(两个不同的内存指针)即使它们相等(它们的成员具有相同的值)。仅仅因为两个对象包含相同的数据并不会使它们成为相同的对象,而是使它们成为两个相等的不同对象。

    这就是为什么o1 == o2o1.Equals(o2); 之间通常存在很大差异的原因。

    例子:

    ComboboxItem item1 = new ComboBoxItem() { Text = "Text", Value = 1 };
    ComboboxItem item2 = new ComboBoxItem() { Text = "Text", Value = 1 };
    ComboboxItem item3 = item1;
    
    item1 == item2      => false
    item1.Equals(item2) => true, if the Equals-method is implemented accordingly
    item1 == item3      => true!! item3 "points to the same object" as item1
    item2.Equals(item3) => true, as above
    

    您需要做的是找到您添加到列表中的同一实例。您可以尝试以下方法:

    this.comboBoxSelektion.SelectedItem = (from ComboBoxItem i in this.comboBoxSelektion.Items where i.Value == 1 select i).FirstOrDefault();
    

    这会从分配给ComboBox 的项目中选择第一个项目,其值为1,并将其设置为选定项目。如果没有这样的项目,null 设置为SelectedItem

    【讨论】:

    • 谢谢。几乎完美。您只需在比较中将 i.value 转换为 int 即可。
    • @Luke:那是因为Value 被声明为object
    【解决方案2】:
    this.comboBoxSelektion.SelectedValue = 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多