简体   繁体   中英

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

refferring to msdn link

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).

First of all override GetHashCode() and Equals() methods in USState type.

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. Then you can remove based on whatever the type T is,

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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