Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have a User Control which contains two Labels. I am using multiple user controls on a form. On click event of user control I have to determine the user control which was clicked. When user clicks outside the label area I can cast the user control from the sender object like:

C#
UserControl1 obj=(UserControl1)sender;


But when user clicks on labels, the label is returned instead of the UserControl.
I want to get UserControl even when the label is clicked.
Posted

I don't have a much clearer solution, but I think this is worth trying. I think you have to customize your own Label class, in my code I call it MyLabel then create a new Click event (with new keyword), then... Here is the detail.

Then if you click the label with some method was subscribed with MyLabel.Click, the sender will be your UserControl (in my code it is UserControl1).
C#
public UserControl1()
        {
            InitializeComponent();
            MyLabel l = new MyLabel();
            l.Text = "Mylabel";
            l.BorderStyle = BorderStyle.FixedSingle;//to help you see its region
            l.Size = new Size(100, 50);
            l.Click += (sender, e) =>
            {
                //This is to test the success
                UserControl u = (UserControl)sender;
                MessageBox.Show(u.Name);
            };
            Controls.Add(l);
        }
       
        public class MyLabel : Label
        {
            public MyLabel()
            {                
                base.Click += (sender, e) =>
                {
                    if(Click != null)
                        Click(this.Parent, e);
                };
            }
            public new event EventHandler Click;            
        }
    }


Hope it helps, If you are still confused, I'm glad to explain more.
 
Share this answer
 
v2
inside label's click event
C#
UserControl1 obj=(UserControl1)yourLable.parent;

In short .Parent is a property you are searching for,
Control.parent returns it's parent control

suppose,
cont2 is placed inside con1
so, Cont2.parent will return cont1
Happy Coding!
:)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900