Search code examples
c#runtimecontextmenustrip

Add context menu strip during runtime in C#


I am trying to add a context menu strip to buttons that are being created during runtime. I am not trying to add new items to a preexisting strip.

Visual Studio is giving me an error saying the index is outside of the bounds. Even though the menu is already prepaid in the designer, Visual Studio is saying that the menu cannot be found.

Code for adding the menu:

btnOutline.ContextMenuStrip = Utilities.Find<ContextMenuStrip>("projectBtnStrip");

Code for Utilities.Find():

public static T Find<T>(string name)
    {
        return (T)Convert.ChangeType(fm.Controls.Find(name, true)[0], typeof(T));
    }

The Find() function does work with all the other types, just not this one. I even created a non generic version, called FindMenuStrip, but that did not work. The goal is to add a menu stip during runtime so the user can add new buttons that have this strip. Any ideas?


Solution

  • You are getting that message because the contextMenuStrip is not part of the form's control collection, so it's not finding that "control". Buttons, labels, textboxes, etc. are in that control collection, not the contextMenuStrip. You'll have to pass it to your method, or maybe use a property to retrieve it.