I have a large list of entities which the user needs to be able to select from. I have a ContextMenuStrip on my window, and has a few MenuItems for each category of entity.
In a library example, think "Staff", "Borrowables", "Patrons", etc...
"Staff" may contain "By Employment Type" -> { "Full Time", "Part Time" } or "By Gender" -> { "Male", "Female" } etc.
"Borrowables" may contain "By Type" -> { "Books", "Magazines", "DVDs" } or "By Genre" -> { "Fiction" -> { "Sci-Fi", "Romance", "Crime" }, "Non-Fiction" { "Science", "Music", "History" } } etc.
Basically, one entity can be in several places at once. A staff member can be full time, and female. A borrowable might be a book, and a romance novel. etc.
I have programatically created a List<ToolStripMenuItem>
together with event handlers, tags, everything. I have then programatically gone through each of them and added them to various menus and sub-menus so that they can be accessed from a variety of places. The idea is that I only need 1 object in memory per ToolStripMenuItem, and if it's checked/unchecked then that should be reflected on all of them.
This would seem to be an elegant solution, and I was really looking forward to seeing it work, but apparently when I add a ToolStripMenuItem to one ToolStripMenuItemDropDownItems, it gets removed from wherever else it was added.
This makes me sad. If they were all the same object, I wouldn't have to write a lot of code to go through and check all matching items when one is checked, because checking one would check them all, and unchecking one would uncheck them all.
Is there any other way I can accomplish this with minimal code?
This is a small example of what I have:
foreach (ToolStripMenuItem item in staffItems)
{
Staff s = (Staff)item.Tag;
foreach (ToolStripMenuItem tsmi in byStaffLocationToolStripMenuItem.DropDownItems)
if ((Location)tsmi.Tag == s.Location)
tsmi.DropDownItems.Add(item); // [1] Item added here
foreach (ToolStripMenuItem tsmi in byStaffTypeToolStripMenuItem.DropDownItems)
if ((StaffType)tsmi.Tag == s.StaffType)
tsmi.DropDownItems.Add(item); // removed from [1] and added here instead :(
}