设置DataSource时从ListBox中删除项目

时间:2013-04-16 03:11:36

标签: c# listbox listboxitem

请参阅我有一个包含多个值的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的原始值,任何建议?

5 个答案:

答案 0 :(得分:2)

尝试

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();
}

答案 1 :(得分:1)

试试这个:

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();
}

答案 2 :(得分:0)

我认为您可以使用linq选择元素,然后使用结果重新分配listBox。这样你就不需要从列表中删除元素,你可以保留HashSet的元素。

答案 3 :(得分:0)

您可以使用BindingSource个对象。使用DataSource绑定它,然后使用RemoveAt()方法。

答案 4 :(得分:0)

尝试一下:

DataRow dr = ((DataRowView)listBox1.SelectedItem).Row;
((DataTable)listBox1.DataSource).Rows.Remove(dr);
相关问题