0

I have a program where I am trying to move items from one arraylist to another via a listbox but when I try to add it to the the second arraylist it does not add there.

ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(new Class(var1, var2, var3, var4, var5, var6, var7));
foreach (object o in list1)
        {
            class m = (class)o;
            selectionBox.Items.Add(m);
        }

I initialised everything above and added everything to the class and then to the listbox. Note the vars I have got from an XML file.

 bool req = true;

        if (selectionBox.SelectedItem != null)
        {
            Count++;
            errorLabel.Text = "";

            for (int i = 0; i < selectionBox.Items.Count; i++)
            {
                if (selectionBox.GetSelected(i) == true)
                {

                    class m = selectionBox.SelectedItem as class;
                    if (m.var2 == ((Modules)selectionBox.Items[i]).var2)
                    {
                        list2.Add(list1.IndexOf(i));
                    }
                }
            }

        }
        else
        {
            errorLabel.Text = "Error";
        }

Here I am trying to add it to the second array list but it does not work the if statement however is correct I have tried this with print statements. So can someone tell me why the following line does not add to the list?

 list2.Add(list1.IndexOf(i));
2
  • It's hard to understand what you are going to do. Can you make it more clear? e.g. What is the use of Count variable? Commented Mar 25, 2013 at 13:35
  • Right I am not sure what has confused you but I will try again, what I am trying to do is read from an xml file and add the values inside tags to variables, I then add those variables to an array list and a listbox. When I move items from one listbox to another I want to move all the vars related with it to the second array list, I hope this clears things up. Commented Mar 25, 2013 at 13:41

1 Answer 1

1

list2.Add(list1.IndexOf(i)); will give you the index (position) of each element. Not the element itself.

To add the element you would need to do something like this:

list2.Add(list1[i]);

Also, just as an aside, this will only copy the reference to each element, it will not create a new copy of each.

Sign up to request clarification or add additional context in comments.

1 Comment

@David Tyron Thanks this has worked for me but it seems to have a bug in when I try to write it to an XML I seem to often get the first tag appearing many times instead of 8 different tags as each variable is different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.