Is there any way to return the name of the control I click on in a window form application using C#?
Using this pointer only returns form name.

Dani AI

Generated

As described, the sender in the menu-item Click handler will be the menu item (so it looks like "Edit"). As hinted, the ContextMenuStrip itself knows which control opened it. Use the ContextMenuStrip.SourceControl property (via the clicked ToolStripItem's Owner) to get the CheckBox you right-clicked, then change its Text or Name.

Example pattern:

private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
    var item = sender as ToolStripItem;
    var cms = item?.Owner as ContextMenuStrip;
    var cb = cms?.SourceControl as CheckBox;
    if (cb != null)
        cb.Text = "New text";
}

Attach the same ContextMenuStrip to each CheckBox (designer or code) so SourceControl is set automatically. If using the legacy ContextMenu (not ContextMenuStrip), track the last right-clicked control in the controls' MouseDown/MouseUp handler (or set the menu's Tag) and read that value in the Edit handler. Always null-check cms/SourceControl because the menu can be shown by keyboard or programmatically and SourceControl may be null. For official details see the ContextMenuStrip.SourceControl documentation: ContextMenuStrip.SourceControl.

Recommended Answers

All 2 Replies

The click event has a sender object, use it to obtain the name. You'll have to attach to the click event of the controls.

ohk! Now i think I might have asked it wrong..
see the scenario is smthng like this..
I have 10 checkboxes in a form... and what i want is when i right click on a checkbox and click edit on the contextmenu then the text value of the checkbox should change..
so what i want is to target the checkbox and that check box out of 10 on whihc i have right clicked..
where as sender object will return "Edit" as we are clicking on the Edit on the context menu.. got it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.