Wednesday, March 16, 2011

Calling a function in a ASP.Net User Control from another User Control on the same page

I recently had to develop a web application in which a page consisted of several user controls. One of the problems I encountered during the development of this page is that I needed User Control A to perform some bit of work, then pass of results and post them into User Control B.

I spent the better part of a day trying to find decent documentation on how to achieve this feat.

You would think you can simply do something like this from User Control A during a button click for example:

ControlB ctrlB = (ControlB)Page.FindControl("cB");
DropDownList ddl = ctrlB.ControlB_DDL;
txtDDLValue.Text = ddl.SelectedValue;

And as long as both controls are referenced on the page this works fine. Unfortunately this is not the case. This would be too easy. While this may work in some situations, it doesn’t seem to hold together well if master pages are used. And in my case nested master pages.

What to do… Well I continued researching and found several interesting articles about using delegates, event bubbling and all sorts of crazy things just to do one relatively simple task. Most of these articles (mostly blog entries) were so bad and hard to follow they aren’t worth reposting here.

In any event, I finally found a solution that worked for my needs. Instead of attempting something difficult and knowing .FindControl(..) wouldn’t work I found out about using .NamingContainer.

In my case my page consisted of a master page, a nested master page, an asp:Panel with an ID=”Data” on the page itself which housed my (destination)user control, and my user control in which I want to to modify data on, and finally the control itself living in that user control.

This code snippet is something I called during an InsertCommand event for a Telerik RadGrid control I happen to be using and takes the little info I want and adds it to a CheckBoxList control housed with my other user control.

CheckBoxList improvementsAddressed = (CheckBoxList)Grid_Improvement
improvementsAddressed.Items.Add(new ListItem(improvement, guid));


I could go into more elaborate detail, but since I’m new to this blogging thing, I’m not even sure if anyone will actually read it. Feel free to leave a comment if you need more details and/or help. But hopefully there’s enough info here to point you in the right direction to get you an elegant solution to your problem.

No comments:

Post a Comment