7.13 Load User Controls Programmatically


7.13 Load User Controls Programmatically

Problem

You need to dynamically build the user interface of a page out of one or more user controls.

Solution

Use the Page.LoadControl method to instantiate the control object from its .ascx file, and then add it to the Controls collection of a container control.

Discussion

User controls are self-contained groups of controls. Like Web forms, user controls consist of a layout portion that defines the contained controls (.ascx file) and a code-behind portion with the event-handling logic (.cs file). User controls allow you to reuse common interface elements on multiple pages and build complex interfaces out of smaller building blocks. One useful characteristic of user controls is that they can be loaded programmatically, which allows you to create a highly configurable interface that you can tailor dynamically according to the user. You simply load the control, configure its properties, and then add it to another container control.

For example, consider the page that generated dynamic graphics in recipe 7.12. The same basic solution could be implemented in a more object-oriented way by creating a custom user control that encapsulates the dynamic graphic. The user control could allow the page to set the text, font, colors, and so on through various properties. Here's an example of what the custom control would look like:

 using System; using System.Web; using System.Web.UI.WebControls; using System.Drawing; using System.Drawing.Drawing2D; public class DynamicGraphicControl : System.Web.UI.UserControl {     // (Designer code omitted.)     private string imageText = "";     public string ImageText {         get {             return imageText;         }         set {             imageText = value;         }     }     private Font textFont;     public Font TextFont {         get {             return textFont;         }         set {             textFont = value;         }     }     private Size imageSize;     public Size ImageSize {         get {             return imageSize;         }         set {             imageSize = value;         }     }     private Color foreColor;     public Color ForeColor {         get {             return foreColor;         }         set {             foreColor = value;         }     }     private Color backColor;     public Color BackColor {         get {             return backColor;         }         set {             backColor = value;         }     }     private Color borderColor;     public Color BorderColor {         get {             return borderColor;         }         set {             borderColor = value;         }     }     private void Page_Load(object sender, System.EventArgs e) {         if (ImageText == "")             return;         // Create an in-memory bitmap where you will draw the image.          Bitmap bitmap = new Bitmap(ImageSize.Width, ImageSize.Height);         // Get the graphics context for the bitmap.         Graphics graphics = Graphics.FromImage(bitmap);         // Set the background color and rendering quality.         // This color will become the border         graphics.Clear(BorderColor);         graphics.SmoothingMode = SmoothingMode.AntiAlias;         // Paint a rectangle.         graphics.FillRectangle(new SolidBrush(BackColor), 5, 5,            ImageSize.Width - 10, ImageSize.Height - 10);         // Set the alignment for the text.         StringFormat stringFormat = new StringFormat();         stringFormat.Alignment = StringAlignment.Center;         stringFormat.LineAlignment = StringAlignment.Center;         // Paint the text.         graphics.DrawString(ImageText, TextFont, new SolidBrush(ForeColor),            new Rectangle(0, 0, ImageSize.Width, ImageSize.Height),            stringFormat);         // Render the image to the HTML output stream.         bitmap.Save(Response.OutputStream,          System.Drawing.Imaging.ImageFormat.Gif);         graphics.Dispose();         bitmap.Dispose();     } } 

The Web form loads this user control in the Page.Load event handler. The user control is placed in a Panel control container. The LoadControl method returns a generic Control object, which the code casts to the appropriate user control class.

 using System; using System.Web; using System.Web.UI.WebControls; using System.Drawing; public class DynamicControlTest : System.Web.UI.Page {     protected System.Web.UI.WebControls.Panel pnl;     // (Designer code omitted.)     private void Page_Load(object sender, System.EventArgs e) {         // Load the control.          DynamicGraphicControl ctrl;         ctrl = (DynamicGraphicControl)           Page.LoadControl("DynamicGraphicControl.ascx");         // Configure the control properties.         ctrl.ImageText = "This is a new banner test";         ctrl.ImageSize = new Size(300, 200);         ctrl.TextFont = new Font("Verdana", 24, FontStyle.Bold);         ctrl.BackColor = Color.Olive;         ctrl.ForeColor = Color.LightYellow;         ctrl.BorderColor = Color.OrangeRed;         // Add the control to the page.         pnl.Controls.Add(ctrl);     } } 

In Visual Studio .NET, the user control class is always available because classes are compiled into a single .dll assembly. If the user control is not a part of the project, however, you won't have the required user control class and you won't be able to access any of the user control's properties or methods . To remedy this problem, you can define a base class or an interface that defines the basic functionality you need to be able to access in any of your custom user controls.

Note  

For an excellent full-scale demonstration of this technique, download the IBuySpy portal case study from http://www.asp.net/IBS_Portal . It demonstrates a highly customizable layout that's built entirely out of dynamically loaded user controls.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net