Remove items from ListBox when DataSource is set

14,168

Solution 1

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

Solution 2

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();
}
Share:
14,168
Reynier
Author by

Reynier

Updated on June 30, 2022

Comments

  • Reynier
    Reynier almost 2 years

    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?