简体   繁体   中英

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. 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:

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.

What is the proper way to remove the non wanted items from the list without remove them from the 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?

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. In that way you dont need to remove elements from the list and you can keep the elements of the HashSet.

You can use BindingSource object. Bind it with DataSource and then use the RemoveAt() method.

Try this :

DataRow dr = ((DataRowView)listBox1.SelectedItem).Row;
((DataTable)listBox1.DataSource).Rows.Remove(dr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM