Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Printable or ReadOnly pages in ASP.NET (code snippet)

You have an ASP.NET page that is full of great controls, functionality, etc. but now you need to print it or render a "readonly" view of the page.  Wouldn't it be nice if there was a little ReadOnly property that you could flip to true on the page and that was it?  Well ... there isn't.  However with a little recursive code, you can achieve the same effect. 

This code snippet is provided to help a few other souls with our same need:
DISCLAIMER:  This code is not perfect but does work as intended and is unit tested (in our application).

Click here for code snippet

The basic approach is loop through all Controls from a certain control down (Page if you choose, since Page is-a Control) and make certain control replacements based on the control that is being evaluated.

The use of Reflection can probably be avoided entirely with a bit of refactoring and use of interfaces instead. Using the string representation of the type name of the Control is a little ugly and could be improved.  Also note that this code makes certain controls not visible such as Button which may not be desirable.  Another approach is to derive your own controls from the base controls and provide a "ReadOnly" rendering - this is probably more work than a simple recursive loop as above.

Comments are welcome.

 

Jonathan Cogley is the CEO and founder of thycotic, a .NET consulting company and ISV in Washington DC.  Our product, myclockwatcher.com is a time and expense tracking system specialized for billable professionals built on ASP.NET, C# and SQL Server using Test Driven Development.

 

2 Comments

Comments have been disabled for this content.