[英]Remove items from ListBox when DataSource is set
See I have a HashSet with several values, this values can contain for example numbers like 4141234567 , 4241234567 , 4261234567 and so on. 见我有一个HashSet的几个值,该值可以包含例如号码,如4141234567,4241234567,4261234567等。 I put a radioButton1 in my UserControl and I want when I click this just the numbers with 414 and 424 remains on my ListBox, for that I wrote this code:
我在我的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);
}
}
}
}
But when I run the code I get this error: 但是,当我运行代码时,我收到此错误:
Items collection cannot be modified when the DataSource property is set.
设置DataSource属性时,无法修改项集合。
What is the proper way to remove the non wanted items from the list without remove them from the HashSet? 从列表中删除不需要的项目而不从HashSet中删除它们的正确方法是什么? I'll add later a optionButton for numbers that begin with 0416 and 0426 and also a optionButton to fill the listBox with original values, any advice?
我稍后会添加一个optionButton用于以0416和0426开头的数字,还有一个optionButton来填充listBox的原始值,任何建议?
try 尝试
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();
}
Try this: 尝试这个:
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();
}
I think that you can select the elements with linq and then reassign the listBox with the result. 我认为您可以使用linq选择元素,然后使用结果重新分配listBox。 In that way you dont need to remove elements from the list and you can keep the elements of the HashSet.
这样你就不需要从列表中删除元素,你可以保留HashSet的元素。
You can use BindingSource
object. 您可以使用
BindingSource
对象。 Bind it with DataSource and then use the RemoveAt()
method. 使用DataSource绑定它,然后使用
RemoveAt()
方法。
Try this : 尝试这个 :
DataRow dr = ((DataRowView)listBox1.SelectedItem).Row;
((DataTable)listBox1.DataSource).Rows.Remove(dr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.