简体   繁体   中英

Detect which Usercontrol on a Form has been clicked

What's my situation? I'm using C#. I have a form with multiple instances of a single usercontrol. The usercontrol has three buttons. Add, Close and Select.

What am I trying to achieve? I want to get the Tag of the user control instance, when its close button is clicked.

Any help would be appreciated,

Thanks

In your Usercontrol, add an eventhandler to the button. Within the Eventhandler fire an event, to which you add an eventhandler in your Form

Edit: Something like this Edit2: Changed it to meet the posters requirements

public delegate void UControlButtonCloseClickedHandler(UControl sender, EventArgs e);
public partial class UControl : UserControl
{
    public event UControlButtonCloseClickedHandler UControlButtonCloseClicked;

    public UControl()
    {
        InitializeComponent();

        btnAdd.Click += ButtonAdd_Click;
        btnSelect.Click += ButtonSelect_Click;
        btnClose.Click += ButtonClose_Click;
    }


    private void ButtonClose_Click(object sender, EventArgs e)
    {
        UControlButtonCloseClicked(this, new EventArgs());
    }
}

And in your Form then just add a handler like uControl.UControlButtonCloseClicked += Hanlder;

Why not link each button to the same event and then get the name of the control to determine if it is the close button (as each control MUST have a unique name, unless you're dynamically adding controls to the form but even at that you should be assigning a name). EDIT: And by getting the name I actually mean comparing if the control that triggered the event is the same one that you want to perform the close action, open action, etc. :)

        public Form1()
    {
        InitializeComponent();
        btnCloseButton.Click += new EventHandler(OnUserControlClick);
        btnOtherRandomButton.Click += new EventHandler(OnUserControlClick);
        btnOtherRandomButton1.Click += new EventHandler(OnUserControlClick);
    }

    private static void OnUserControlClick(object sender, EventArgs e)
    {
        if (sender as UserControl == btnCloseButton)
        {
            this.Close();
        }
    }

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