How to extend an existing ContextMenuStrip?

I've a common ContextMenuStrip for every workspace control of my application. This ContextMenuStrip contains 4 Items ("Move front", "Move back", and "Delete control").

Now I want to extend it for one control. There's a DataGridView on this control and I want an additional item to delete the selected DataGridViewRow.

This is the code I tried:

    private void extendContextMenuOfDataGridViewRow (DataGridViewRow row) {
        ContextMenuStrip ctx = new ContextMenuStrip();
        foreach (ToolStripMenuItem item in this.ContextMenuStrip.Items) {
            ctx.Items.Add(item);
        }
        ctx.Items.Add(new ToolStripSeparator());
        ToolStripMenuItem ctxDeleteRow = new ToolStripMenuItem("Delete row");
        ctxDeleteRow.Name = "ctxDeleteRow";
        ctxDeleteRow.Click += new EventHandler(ctxDeleteRow_Click);
        ctx.Items.Add(ctxDeleteRow);

        row.ContextMenuStrip = ctx;
    }

After the first item of the foreach loop was added to ctx.Items the debugger leaves the whole method and the first item is missing at the common ContextMenuStrip.

How do I do that right?

Answers


If you want to extend functionally of some control, you can either

a) create an extension method

public void DoSomething(this MyExtendedControl mec, DataGridViewRow row)
{
}

b) create a new class inheriting from your unsatisfactory control (or even create a completely new control), when you can override/add things as needed

Depends on your specific needs, couldn't understand from your description...


I haven't worked with WinForms for ages, but are you sure that you can keep the same Row object assigned to two different Strips at once?

foreach (ToolStripMenuItem item in this.ContextMenuStrip.Items) {
    ctx.Items.Add(item);
}

I seriously doubt this should work by design because a row has to “talk” to its parent, and by adding it to another strip I'm afraid you're re-assigning the parent.

Instead, I would have added an item to the common menu but with its Visible property to false. Then I would catch the menu opening event and make item visible if target is a DataGridViewRow.


Need Your Help

mmenu plugin check if sliding is finished

javascript jquery html css mmenu

I have some CSS that adds a div across the whole page.

PHP and Django: Nginx, FastCGI and Green Unicorn?

php django nginx fastcgi

I'm curious... I'm looking to have a really efficient setup for my slice for a client. I'm not an expert with servers and so am looking for good solid resources to help me set this up... It's been