0

基本上我正在创建一个程序,该程序将信息从 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]);
    }
}
4

2 回答 2

3
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方法。但是,您可能错过了一个关键点。

您使用什么类型的项目来填充您的ListBox? Exists默认情况下,将调用.Equalswhich 使用引用相等。因此,如果您需要根据值进行过滤,则需要覆盖.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.

于 2012-06-14T21:47:45.247 回答
1

这应该为你做...

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

    }
于 2012-06-14T21:54:45.860 回答