0

I have this task to be done : there is a contextmenustrip, where in one of the branches there are 3 static items (created via designer) and after that there will be dynamically created items (links to subfolders of one folder on hard drive). Here it is part of the code i am using to create items :

    private void listBox1_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right && listBox1.SelectedIndex != -1)
        {
            string pathDatosString = Path.Combine(PMVars.MainPath + clientsbox2.SelectedItem.ToString() + @"\" + listBox1.SelectedItem.ToString() + @"\01-Datos");

                int count = ((contextMenuStrip1.Items[2] as ToolStripMenuItem).DropDownItems[2] as ToolStripMenuItem).DropDownItems.Count;
                //MessageBox.Show(count.ToString());
                if (count > 3)
                {
                    for (int i = 3;i < count;i++)
                    {
                        ((contextMenuStrip1.Items[2] as ToolStripMenuItem).DropDownItems[2] as ToolStripMenuItem).DropDownItems.RemoveAt(i);
                    }

                }
            if (Directory.Exists(pathDatosString))
            {
                // This path is a directory
                foreach (string diritem in Directory.GetDirectories(pathDatosString))

                {
                    ToolStripMenuItem item = new ToolStripMenuItem();
                    item.Click += new EventHandler(OpenDir);
                    string dirCutted = diritem.Split('\\').Last();
                    ((contextMenuStrip1.Items[2] as ToolStripMenuItem).DropDownItems[2] as ToolStripMenuItem).DropDownItems.Add(dirCutted, null, OpenDir) ;
                }
            }
            contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
        }

    }

So the problem i've encountered is that each time listbox1_mouseclick is being started - item is being created again and again (clones) So i tried to made a check if item with text already exists , but error pops out saying that collection has been changed. I think that's because of the dynamically created items i am collecting ? This code works for deleting, but maybe there is more elegant solution for this?

tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

0

Prior to adding the items, call the Clear() method of your DropDown. You're scanning for folders everytime, so it makes sense to start with a clean slate. Every point in the tree that has sub-items, and to which you add dynamically, is subject to this need to Clear() first.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
  • Thanks for your answer, but i cannot because as i've said i have already 2 items, which need to be present all the time. – Oleg.Budeanu Jun 14 '13 at 13:24