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?