[英]How to remove an item from listbox with datasource set, using string in C#
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.