以编程方式调用 WinForms contextmenustrip

发布于 2024-08-26 22:55:05 字数 515 浏览 12 评论 0原文

我在 c# windows 程序中以编程方式创建一个图片框。我为它分配了 Tag 属性的值。我想以编程方式打印出该标签号,仅用于测试目的。所以我尝试这样做:

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());
}

但是当我右键单击图片并单击菜单项时,它给了我一个例外。 “未处理 NullReferenceException”“未将对象引用设置为对象的实例。”。有人知道发生了什么事吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

喜爱皱眉﹌ 2024-09-02 22:55:05

该行将

PictureBox pic = sender as PictureBox;

pic 设置为 null,因为这是 ContextMenuStrip 的事件处理程序,而不是 PictureBox 的事件处理程序。

sender 参数是对您添加事件处理程序的对象的引用 - 即 ContextMenuStrip

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.

触ぅ动初心 2024-09-02 22:55:05

看起来 pic.Tag 为 null,因此 .ToString 正在强制异常。您应该这样做:

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

确保您将标记设置为某处,例如在 Form1_Load 中:

pic.Tag = someValue;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文