![](/img/trans.png)
[英]How to remove selected items from ListBox when a DataSource is assigned to it in C#?
[英]Remove items from ListBox when DataSource is set
见我有一个HashSet的几个值,该值可以包含例如号码,如4141234567,4241234567,4261234567等。 我在我的UserControl中放了一个radioButton1,当我点击这个时,我想要414和424的数字保留在我的ListBox上,因为我编写了这段代码:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
var bdHashSet = new HashSet<string>(bd);
if (openFileDialog1.FileName.ToString() != "")
{
foreach (var item in bdHashSet)
{
if (item.Substring(1, 3) != "414" || item.Substring(1, 3) != "424")
{
listBox1.Items.Remove(item);
}
}
}
}
但是,当我运行代码时,我收到此错误:
设置DataSource属性时,无法修改项集合。
从列表中删除不需要的项目而不从HashSet中删除它们的正确方法是什么? 我稍后会添加一个optionButton用于以0416和0426开头的数字,还有一个optionButton来填充listBox的原始值,任何建议?
尝试
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
var bdHashSet = new HashSet<string>(bd);
listBox1.Datasource = null;
listBox1.Datasource = bdHashSet.Where(s => (s.StartsWith("414") || s.StartsWith("424"))).ToList();
}
尝试这个:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
var bdHashSet = new HashSet<string>(bd);
listBox1.Datasource = bdHashSet.Select(s => (s.Substring(1, 3) == "414" || s.Substring(1, 3) == "424"));
//After setting the data source, you need to bind the data
listBox1.DataBind();
}
我认为您可以使用linq选择元素,然后使用结果重新分配listBox。 这样你就不需要从列表中删除元素,你可以保留HashSet的元素。
您可以使用BindingSource
对象。 使用DataSource绑定它,然后使用RemoveAt()
方法。
尝试这个 :
DataRow dr = ((DataRowView)listBox1.SelectedItem).Row;
((DataTable)listBox1.DataSource).Rows.Remove(dr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.