Programatically creating context menu I have the need to programatically create a context menu using names for the menu items which aren't known until the program loads user data.

Here's how I have implemented it.  I'm not happy with the cast to get the menu item text to find out which item they have clicked on. Is there a better way that I'm missing?

public partial class Form1 : Form
{
    private readonly string[] cards = new string[] {"HBOS", "EGG", "RBOS"};

    ContextMenu mnuContextMenu = new ContextMenu();

    private void Form1_Load(object sender, EventArgs e)
    {
        ContextMenu = mnuContextMenu;

        SetupRightClickmenu();
    }

    private void SetupRightClickmenu()
    {
        MenuItem bank1MenuItem = new MenuItem(BankNames.Bank1);
        MenuItem bank2MenuItem = new MenuItem(BankNames.Bank2);
        MenuItem bank3MenuItem = new MenuItem(BankNames.Bank3);
        MenuItem cashMenuItem = new MenuItem("Cash");
        MenuItem creditCardMenuItem = new MenuItem("Credit Card");

        bank1MenuItem.Click += bank1MenuItem_Click;
        bank2MenuItem.Click += bank2MenuItem_Click;
        bank3MenuItem.Click += bank3MenuItem_Click;
        cashMenuItem.Click += cashMenuItem_Click;

        mnuContextMenu.MenuItems.Add(bank1MenuItem);
        mnuContextMenu.MenuItems.Add(bank2MenuItem);
        mnuContextMenu.MenuItems.Add(bank3MenuItem);
        mnuContextMenu.MenuItems.Add(cashMenuItem);
        mnuContextMenu.MenuItems.Add(creditCardMenuItem);


        MenuItem creditCardSubMenuItem;

        foreach(string card in cards)
        {
            creditCardSubMenuItem = new MenuItem();
            creditCardSubMenuItem.Text = card;
            creditCardMenuItem.MenuItems.Add(creditCardSubMenuItem);
            creditCardSubMenuItem.Click += creditCardSubMenuItem_Click;
        }
    }

    void creditCardSubMenuItem_Click(object sender, EventArgs e)
    {
        MenuItem menuItem = (MenuItem) sender;

        MessageBox.Show("You clicked on " + menuItem.Text);
    }

    void cashMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on cash");
    }

    void bank3MenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on bank 3");
    }

    void bank2MenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on bank 2");
    }

    void bank1MenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked on bank 1");
    }
}


In the actual version the cards array is received from the users data.
You can use the Tag property to store the card.  Its normal to store the context object in the Tag.

that way you can make the text whatever you like eg..

creditCardSubMenuItem.Text = string.Format("The card {0}", card);
creditCardSubMenuItem.Tag= card;