Calling WinForms programs contextmenustrip

I programmatically create a Picture Box in a C # windows program. I assign it the value of the Tag property. I would like to print this tag number programmatically, for testing purposes only. 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. "NullReferenceException was unhandled" "Object reference not set to object instance." did anyone understand what was going on?

+3
source share
2 answers

Line

PictureBox pic = sender as PictureBox;

sets pic to null since it is an event handler for ContextMenuStrip, not for PictureBox.

sender - , , - < <21 > .

+2

, pic.Tag null, .ToString . :

if(pic.Tag != null)
    MessageBox.Show(pic.Tag.ToString());

, - someowhere, , Form1_Load:

pic.Tag = someValue;
0

Source: https://habr.com/ru/post/1738744/


All Articles