以编程方式调用 WinForms contextmenustrip
我在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该行将
pic 设置为 null,因为这是
ContextMenuStrip
的事件处理程序,而不是PictureBox
的事件处理程序。sender
参数是对您添加事件处理程序的对象的引用 - 即ContextMenuStrip
。The line
sets pic to null, since this is an event handler for the
ContextMenuStrip
, and not for thePictureBox
.The
sender
parameter is a reference to the object you added the event handler to - that's theContextMenuStrip
.看起来 pic.Tag 为 null,因此 .ToString 正在强制异常。您应该这样做:
确保您将标记设置为某处,例如在 Form1_Load 中:
Looks like pic.Tag is null so the .ToString is forcing the exception. You should do this:
Make sure you are setting tag to something someowhere, like in the Form1_Load: