How to copy text from different Labels using only

2019-07-18 20:13发布

问题:

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:

  1. right click on labelA
  2. Context menu pops up with copy, and select it
  3. System recognizes that labelA was right clicked on so takes the text from the Label. Clipboard.SetText(labelChosen)
  4. then if user wants to click labelC that will be choosen.

I just do not want to create 10 context menus to do this.

回答1:

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):

Clipboard.SetText(labelContextMenuStrip.SourceControl.Text);

You can then assign the ContextMenuStrip to each desired label's ContextMenuStrip property in the designer, or programmatically, in your Form's Load or Shown event:

foreach (var label in Controls.OfType<Label>())
{
    label.ContextMenuStrip = labelContextMenuStrip;
}

Full code (verified solution):

private void Form1_Load(object sender, EventArgs e)
{
    // Optional - can be manually set in the Designer
    foreach (var label in Controls.OfType<Label>())
    {
        label.ContextMenuStrip = labelContextMenuStrip;
    }
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
    Clipboard.SetText(labelContextMenuStrip.SourceControl.Text);
}