I have a Windows Form program for contact list. I already have a context menu used for copy and pasting from the DataGridView.
However, I want to be able to right click a Label and select copy from a context menu to copy the data from that ONE Label.
I have 10 different Labels, I do NOT want all of them, just the one that I right clicked on to select copy.
I know that using Clipboard.SetText(label1.text)
will let me select that specific Label, but I do not what to create 10 context Labels that I should be able to do with one.
If I wanted to select all of the text boxes I can do this.
string UserInfo = $"{lblFirstName.Text}\n" +
$"{lblLastName.Text}\n" +
$"{lblEmailAddress.Text}\n" +
$"{lblPhysicalAddress.Text}\n" +
$"{lblCountry.Text}\n" +
$"{lblCompany.Text}\n" +
$"{lblStatus.Text}\n" +
$"{lblFirstContact.Text}\n" +
$"{lblLastContact.Text}\n" +
$"{lblNotes.Text}\n ";
Clipboard.SetText(UserInfo);
For the DataGridView was easy. But this is for the use to right click on ONE Label to do the copy.
I created a 2nd ContextMenuStrip and what SHOULD occur:
- right click on
labelA
- Context menu pops up with copy, and select it
- System recognizes that
labelA
was right clicked on so takes the text from the Label.Clipboard.SetText(labelChosen)
- then if user wants to click
labelC
that will be choosen.
I just do not want to create 10 context menus to do this.
EDITED - Thanks to @Jimi for this suggestion, via comments
Simplest solution is to add the
ContextMenuStrip
control to your Form from the toolbox, and configure an item - "Copy"; double-click the item, and use the following code in the event handler (presuming your context menu strip is called labelContextMenuStrip):You can then assign the ContextMenuStrip to each desired label's
ContextMenuStrip
property in the designer, or programmatically, in your Form'sLoad
orShown
event:Full code (verified solution):