Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling WinForms contextmenustrip programmatically

I programmatically create a Picture Box in c# windows program. I assign it with a value for the Tag property. I would like to print out that tag number programmatically, just for test purposes. so I try this:

private void Form1_Load(object sender, EventArgs e)
{
    pic.ContextMenuStrip = contextMenuStrip1;
    pic.ContextMenuStrip.Click += new EventHandler(this.MyPicHandler);
}

void MyPicHandler(object sender, EventArgs e)
{
    PictureBox pic = sender as PictureBox;

    MessageBox.Show(pic.Tag.ToString());
}

But when I right-click on the picture, and click on the menu item, it gives me an exception. "A NullReferenceException was unhandled" "Object reference not set to an instance of an object.". anyone's got an idea what's going on?

like image 484
jello Avatar asked May 25 '26 00:05

jello


1 Answers

The line

PictureBox pic = sender as PictureBox;

sets pic to null, since this is an event handler for the ContextMenuStrip, and not for the PictureBox.

The sender parameter is a reference to the object you added the event handler to - that's the ContextMenuStrip.

like image 176
John Saunders Avatar answered May 26 '26 13:05

John Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!