Click here to Skip to main content
15,898,010 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If we have 2 user controls on a page, and on click event of UserControl1_Button should set value (say Text) of UserControl2_Label. How is it posible? I arleady tried with using base.Parent.FindControl. It can go only upto Parent controls.
Posted
Updated 26-Mar-12 1:44am
v2

Even if you find a way to do this, it will be bad design.

1. UserControl1 is aware of UserControl2's implementation details. That's bad design. You should program against an interface, not against implementation.
2. It would be better if we can leave the task of changing UserControl2's label to itself.

Define an event in UserControl1. Fire the event when that particular button of UserControl1 is clicked. Then the other control should be able to listen to that event and perform any action it wants.

Benefits of this approach:

1. No matter what happens to UserControl2's code, UserControl1 need not to change.
2. You can reuse the button click event of UserControl1 for other GUI objects as well.
 
Share this answer
 
Comments
tgurinder 26-Mar-12 23:59pm    
Thanks Krumia for your feedback and solution. It was an interview question and i tried few options on my side as well. Posting my solution in few minutes and it may not be the best solution, Will look for delegates as well.
Find UserControl2 in Parent page and then Find Label control inside UserControl2 .
Here is the solution. Will post robust solution asap.

C#


C#
protected void Button1_Click(object sender, EventArgs e)
{
      UserControl  uc = base.Parent.FindControl("uc2") as UserControl;
       if (uc != null)
       {
         uc.FindControl("lblUserControl2") as Label).Text  = "its from usercontrol1 Button click event ";
       }
}
 
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