如何限制Combobox添加重复值?

时间:2012-05-09 11:52:14

标签: c#

我有一个用于向Combobox添加值的类(一个用于显示,另一个用于隐藏)

public class ComboBoxItem
    {
        string displayValue;
        string hiddenValue;

    //Constructor
    public ComboBoxItem(string displayVal, string hiddenVal)
    {
        displayValue = displayVal;
        hiddenValue = hiddenVal;
    }

    //Accessor
    public string HiddenValue
    {
        get
        {
            return hiddenValue;
        }            
    }
    //Override ToString method
    public override string ToString()
    {
        return displayValue;
    } 

使用此类我将值添加到Combobox

cmbServerNo.Items.Add(new ComboBoxItem(strIPAddress, iConnectionID.ToString()));

但我想限制重复值,我正在使用以下方法

foreach (KeyValuePair<int, Object> ikey in m_lstConnectionID)
            {
                if (!cmbServerNo.Items.Contains(strIPAddress))
                {
                    cmbServerNo.Items.Add(new ComboBoxItem(strIPAddress, iConnectionID.ToString()));
                }
            } 

但它猜它添加strIpAddress和ConnectionID所以当我检查它包含它失败。 如何解决这个问题? 谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用LINQ的Any扩展方法:

if (!cmbServerNo.Items.Any(x => x.ToString() == strIPAddress))
{
    cmbServerNo.Items.Add(new ComboBoxItem(strIPAddress,
                                           iConnectionID.ToString()));
}

答案 1 :(得分:0)

您可以使用HashSet(MSDN

HashSet<String> items = new HashSet<String>();
foreach (KeyValuePair<int, Object> ikey in m_lstConnectionID)
            {
                if (!items.Contains(strIPAddress))
                {
                    items.Add(strIPAddress);
                    cmbServerNo.Items.Add(new ComboBoxItem(strIPAddress, iConnectionID.ToString()));
                }
            } 

答案 2 :(得分:0)

如果要使用ListBox或ComboBox中的Items.Contains函数,该对象需要实现IEquatable接口。

这样的事情:

public class ComboBoxItem : IEquatable<ComboBoxItem> {
  // class stuff

  public bool Equals(ComboBoxItem other) {
    return (this.ToString() == other.ToString());
  }

  public override bool Equals(object obj) {
    if (obj == null)
      return base.Equals(obj);

    if (obj is ComboBoxItem)
      return this.Equals((ComboBoxItem)obj);
    else
      return false;
  }

  public override int GetHashCode() {
    return this.ToString().GetHashCode();
  }
}

现在Items.Contains应该像这样工作:

// this should be added:
ComboBoxItem addItem = new ComboBoxItem("test", "test item");
if (!cb.Items.Contains(addItem)) {
  cb.Items.Add(addItem);
}

// this should not be added:
ComboBoxItem testItem = new ComboBoxItem("test", "duplicate item");
if (!cb.Items.Contains(testItem)) {
  cb.Items.Add(testItem);
}
相关问题