ASP.NET: Exposing a Web User Control’s controls

asp.netuser-controls

I've created some Web User Controls (.ascx files) and dropped them into Pages. The user controls have some TextBoxes in them that I'd like the Page to be able to access directly.

What's the easiest (read: least time) way to expose these TextBoxes in the user controls to the Pages containing the user controls?

The two options I know are calling myUserControl.FindControl(id) from the Pages (does this even work from the Page?), and writing properties in the user controls to expose the TextBox values.

Neither seem ideal. FindControl() requires the Page know the IDs of the TextBoxes in the user controls, thereby breaking encapsulation and adding hard-coded strings, and writing a bunch of properties in the user controls will be very time consuming given the number of TextBoxes in these user controls.

There's no way to declare these TextBoxes in my user controls be public instead of protected?

Best Answer

(Setting aside the obvious comments about the fact that what you're describing is essentially the opposite of best practice...)

If you are using a Web Application type project, you should have a designer.cs file for each UserControl. That contains the declaration of each child control, so you can change the access modifier to public.

If you are using a Web Site type project, you should probably convert to Web Application. According to Microsoft (and backed up by experience), the Web Site type is not intended for use when you plan to write extensive code which spans beyond a single code-behind.

Related Topic