简体   繁体   中英

C# delete 2 dynamic controls based only on the first controls clicked

I have some dynamically created PictureBox 's and Label 's for each PictureBox , and a ContextMenu with a ToolStripMenuItem named "Remove" ... I want to remove only the PictureBox and the Label that is related to that PictureBox that is clicked but this ContextMenu is attached to all PictureBox 's only, and not to Label 's.

Is there a way to delete two controls in one click based only on the first one clicked ?

How to do it ?

Store a reference to the associated Label in the Tag() property of the PictureBox when you create them:

Label lbl = new Label();
PictureBox pb = new PictureBox();
pb.Tag = lbl;

Later you can remove them both:

// ...assuming "pb" now refers to the PictureBox that fired the ContextMenu...
((Control)pb.Tag).Dispose();
pb.Dispose();

You could store the id of another control in the first control as its attribute. Now you could delete the second control using the attribute in the first control click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM