BLOGS BY TOPIC
BLOGS BY AUTHOR
BLOGS BY YEAR
User controls are the key to using ASP.NET effectively - this blog explains how and why to create and use user controls, with code examples for VB and C#.
- User Controls in ASP.NET
- How the User Controls will Work for our Case Study (this blog)
- Raising Events for User Controls - Visual Basic
- Raising Events from User Controls in C#
- Problems with User Controls in ASP.NET
Posted by Andy Brown on 17 October 2012
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
How the User Controls will Work for our Case Study
Breaking Down a Page into User Controls
Our system consists of 3 parts:
- A search form (which we'll put into a separate user control called ucTaskSearch).
- A user control to list out the to-do tasks returned, which we'll call ucTaskList.
- A user control allowing you to see the details for a single task, called ucTaskRecord.
You could put each of these 3 parts in separate web pages, but you'll then have all of the problems of passing information between pages and maintaining state. Insofar as possible in ASP.NET you should have a few complicated pages, rather than a lot of simple ones which talk to each other.
Here's what our 3 user controls will look like:
At any time you'll only be able to see one of these three user controls at a time (the other two will be hidden).
You could create this form by putting each of the 3 parts into separate ASP.NET panels, and hiding and displaying these as necessary. However, user controls are easier to code (see below).
Advantages of the User Control Approach
Why bother with user controls? Why not just use panels, as in the hint above?
My moment of epiphany was when I was building my first big ASP.NET website, and reached 3,000 lines of code in a single page. The whole project was becoming unmanageable - and the solution was to break the page down into several different user controls.
User controls give two main advantages:
|Reusable modules||You could (for example) stick the ucTaskList user control on any page and it would work equally well.|
|Simplicity||Although getting the user controls to talk to each other is tricky, once you've done this each user control is far easier to use and maintain.|
Raising Events - Getting User Controls to Talk to Each Other
I've skirted round this issue so far, but it's time now to consider what the user controls need to say to each other. Here's a diagram showing this (I've missed out the Cancel buttons to keep the diagram simple):
The flow of information between our user controls.
With this diagram in mind, we'll now look at how to the various user controls. I'll show this in two separate parts (one for VB, one for C#).