Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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:
 
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 25-Sep-12 1:22am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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).
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.
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

inside label's click event
   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!
Smile | :)
  Permalink  

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



Advertise | Privacy | Mobile
Web01 | 2.8.1411022.1 | Last Updated 25 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100