【问题标题】:How to get a list box to disallow duplicate items?如何让列表框禁止重复项?
【发布时间】:2012-06-14 21:45:27
【问题描述】:

基本上我正在创建一个程序,该程序将信息从 xml 文件读取到 lisbox 并允许用户将列表框中的项目传输到另一个列表框。

但我想知道如何禁止将多个项目从一个列表框导入到另一个列表框。我想我可以通过某种方式来检查字符串是否已经存在于列表框中。

我想这样做的原因是因为用户可以点击 x 次来导入项目,这是不专业的。

任何帮助将不胜感激。

private void button1_Click(object sender, EventArgs e)
{
    if (!listBox.Items.Exists) // Random Idea which doesnt work
    {
        listBox2.Items.Add(listBox1.Items[listBox1.SelectedIndex]);
    }
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:
    private void button1_Click(object sender, EventArgs e)
    {
        if (!listBox.Items.Exists) // Random Idea which doesnt work
        {
        listBox2.Items.Add(listBox1.Items[listBox1.SelectedIndex]);
        }
    
    }
    

    这实际上会起作用,但您需要使用Contains 方法。但是,您可能遗漏了一个关键点。

    您使用什么类型的项目来填充您的ListBoxExists 将调用 .Equals,默认情况下使用 reference 相等。因此,如果您需要根据值进行过滤,则需要为您的类型覆盖 .Equals 并更改语义。

    例如:

    class Foo 
    { 
        public string Name { get; set; }
        public Foo(string name)
        {
            Name = name;
        }
    }
    
    class Program
    {
        static void Main( string[] args )
        {
            var x = new Foo("ed");
            var y = new Foo("ed");
            Console.WriteLine(x.Equals(y));  // prints "False"
        }       
    }
    

    但是,如果我们重写 .Equals 以提供值类型语义...

    class Foo 
    { 
        public string Name { get; set; }
        public Foo(string name)
        {
            Name = name;
        }
    
        public override bool Equals(object obj)
        {
            // error and type checking go here!
            return ((Foo)obj).Name == this.Name;
        }
    
        // should override GetHashCode as well
    }
    
    class Program
    {
        static void Main( string[] args )
        {
            var x = new Foo("ed");
            var y = new Foo("ed");
            Console.WriteLine(x.Equals(y));  // prints "True"
            Console.Read();
        }       
    }
    

    现在您对if(!listBox.Items.Contains(item)) 的调用将按照您的预期进行。但是,如果您希望它继续工作,您需要将该项目添加到两个列表框中,而不仅仅是 listBox2

    【讨论】:

    • OP 说所有项目都已经存在于 listBox1 中 - 所以这个解决方案似乎过于复杂......如果项目已经存在于另一个列表框中,我发布的简单包含解决方案似乎更合乎逻辑。只是我的想法,但你已经明白了;-)
    • @Vijay:我也推荐了Contains,但是如果他创建一个具有相同值的新实例并进行比较,它仍然会失败。 OP 没有向我们展示他从 哪里 获取这些实例,所以我扩展了一点,以防他接下来遇到这个问题。不过你是对的;如果他不需要覆盖 Equals 他不应该。
    【解决方案2】:

    这应该为你做......

    private void button1_Click(object sender, EventArgs e)
        {
            if (!ListBox.Items.Contains(listBox1.SelectedItem)) // Random Idea which doesnt work
            {
            listBox2.Items.Add(listBox1.SelectedItem);
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多