views:

404

answers:

1

The CheckBox in my form won't remove items from the listbox at all if it is unchecked, even though I have it in the correct events

private void WWW_checkbox_Checked(object sender, RoutedEventArgs e)
{
    packagelist_listbox.Items.Remove(SelectaCategory_listbox);
    LoadPackageList.Load("www.xml");
    XmlNodeList WWWPackageList = LoadPackageList.SelectNodes("/Packages/*");
    int countthenodes = 0;



    //Removes the text "Select A Category" and refrehes the form

    foreach (XmlNode WWWPackages in WWWPackageList)
    {


        //Adds each attribute to the apropriate variable
        WWWPackageTitle.Add(WWWPackages.Attributes["title"].Value.ToString());
        WWWPackageInfoPage.Add(WWWPackages.Attributes["infopage"].Value.ToString());
        WWWPackageDLURL.Add(WWWPackages.Attributes["dlurl"].Value.ToString());
        WWWPackageID.Add(WWWPackages.Attributes["id"].Value.ToString());
        if (WWW_checkbox.IsChecked == true)
        {
            packagelist_listbox.Items.Add(WWWPackageTitle[countthenodes]);
        }


        countthenodes++;
    }
    packagelist_listbox.Items.Refresh();
    Refresh(packagelist_listbox);
}





private void WWW_checkbox_Click(object sender, RoutedEventArgs e)
{

    if (WWW_checkbox.IsChecked == false)
    {
        foreach (string EachPackageWWW in WWWPackageTitle)
        {
            packagelist_listbox.Items.Remove(packagelist_listbox.Items.Contains(EachPackageWWW));
        }
    }
    packagelist_listbox.Items.Refresh();
    Refresh(packagelist_listbox);




}

The Refresh works correctly because It will add the same content to the listbox everytime you check it

+3  A: 

The problem is in this line:

packagelist_listbox.Items.Remove(packagelist_listbox.Items.Contains(EachPackageWWW));

If you break that apart, it's doing this:

bool doesListContainsPackage = packagelist_listbox.Items.Contains(EachPackageWWW);
packagelist_listbox.Items.Remove(doesListContainPackage);

I.e. you're removing the boolean result of the Contains(item) method, not the item itself.

Change this to:

packagelist_listbox.Items.Remove(EachPackageWWW);

or

if (packagelist_listbox.Items.Contains(EachPackageWWW))
  packagelist_listbox.Items.Remove(EachPackageWWW));

if you want to be ultra-cautious.

By the way, you might want to consider using the Unchecked event (for symmetry with Checked) rather than the Click event.

itowlson