Reputation: 103
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");
Upvotes: 2
Views: 1882
Reputation: 31097
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.
Upvotes: 0
Reputation: 94643
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";
Upvotes: 1
Reputation: 7489
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");
Upvotes: 0