简体   繁体   English

如何使用C#中的字符串从设置了数据源的列表框中删除项目

[英]How to remove an item from listbox with datasource set, using string in C#

refferring to msdn link 引用到msdn链接

how can I remove an item using string??? 如何使用字符串删除项目??? (I don't want to remove it by using selected index) (我不想使用选定的索引将其删除)
I want something like 我想要类似的东西

USStates.Remove("Alabama","AL");

You can't change Items collection but you can change the DataSource (List or ArrayList). 您不能更改Items集合,但是可以更改DataSource(列表或ArrayList)。

First of all override GetHashCode() and Equals() methods in USState type. 首先,以USState类型重写GetHashCode()Equals()方法。

public override int GetHashCode()
{
     return myLongName.GetHashCode() + myShortName.GetHashCode();
} 
public override bool Equals(object obj)
{
     return GetHashCode() == obj.GetHashCode();
} 

Now, you can remove an element, 现在,您可以删除一个元素,

 listBox1.DataSource = null; // Set null so you can update DataSource
 USStates.Remove(new USState("Wisconsin", "WI"));
 listBox1.DataSource = USStates;
 listBox1.DisplayMember = "LongName";
 listBox1.ValueMember = "ShortName"; 

First of all, don't use an ArrayList, use a List. 首先,不要使用ArrayList,而要使用List。 Then you can remove based on whatever the type T is, 然后,您可以根据类型T删除

    list.Remove("whatever"); 

Updated: I assume you add a button that you can click to remove an item. 已更新:我假设您添加了一个按钮,可以单击该按钮来删除项目。

    BindingList<USState> USStates;
    public Form1()
    {
        InitializeComponent();

        USStates = new BindingList<USState>();
        USStates.Add(new USState("Alabama", "AL"));
        USStates.Add(new USState("Washington", "WA"));
        USStates.Add(new USState("West Virginia", "WV"));
        USStates.Add(new USState("Wisconsin", "WI"));
        USStates.Add(new USState("Wyoming", "WY"));

        listBox1.DataSource = USStates;
        listBox1.DisplayMember = "LongName";
        listBox1.ValueMember = "ShortName";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var removeStates = (from state in USStates
                            where state.ShortName == "AL"
                            select state).ToList();
        removeStates.ForEach( state => USStates.Remove(state) );
    }

PS: I thought you're using WPF in my previous answer. PS:我以为您在上一个答案中使用WPF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM