开发者

calling WinForms contextmenustrip programmatically

开发者 https://www.devze.com 2022-12-24 15:34 出处:网络
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 t

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 se开发者_运维知识库nder, 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?


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.


Looks like pic.Tag is null so the .ToString is forcing the exception. You should do this:

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

Make sure you are setting tag to something someowhere, like in the Form1_Load:

pic.Tag = someValue;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号