Creating Custom Web Controls in C# Stats
Rating: 4.75 out of 5 by 4 users
Submitted: 04/09/01
Peter Weng (lateboy@mit.edu)
--------------------------------------------------------------------------------
By now you may or may not have heard of ASP.NET's Web Controls. In this tutorial I plan to discuss the advantages of using Web Controls, as well as how to create and deploy them in C#.
What are Web Controls?
Web Controls are widgets that can be reused across multiple webpages. Controls may render HTML to the client, or other formats such as WML or XML. If you're familiar with ASP.NET, you'll know that ASP.NET provides some controls for you right out of the box. These include DataGrids, Calendars, AdRotators, etc.
Why use User Controls?
The biggest advantage of Web Controls is code reuse. Because they can be reused across multiple pages in different ways, Web Controls can save you the hassle of writing similar HTML on multiple pages by generating the appropriate HTML for you.
But why use C#? Can't we just use .ascx files?
.ascx files are another way of creating reusable controls. However, it doesn't always provide a clean way of separating your code from content. What this means is that content developers can write content, graphic artists and UI experts can layout your site, and you can develop the logic behind everything without overlapping each other. In addition, when deploying your web site or giving your web site to someone else, by using controls written in C# and pre-compiled, you won't have to give them any of your source code to launch your site, all you need to give them are the dll's which contain your compiled source code for your control.
What are we going to build today?
Today we'll be taking apart one of the components of DevHood. If you look at the top of most of our pages, you'll notice a Yahoo! style navigation bar that looks something like this:
Home > Tutorials > General ASP.NET > Creating Custom Web Controls
This navigation bar is actually generated dynamically for each page by a Custom Web Control. Let's start by looking at the first part of the code.
namespace MyNavBar {
using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections;
using System.Drawing;
We begin by giving our Web Control a namespace, so that we can reference it in other pages. We'll also import all the namespaces we'll need for our Web Control. On .aspx pages, the following namespaces are imported by default, but for Web Controls in .cs files, you'll need to import them yourself if you'll need them:
System
System.Web
System.Web.UI
System.Web.UI.HtmlControls
System.Web.UI.WebControls
System.Collections
System.IO
public class NavBar : WebControl {
private string strSeperator = ">";
private int iRPad = 3;
private int iLPad = 1;
public string Seperator {
get {return strSeperator;}
set {strSeperator = value;}
}
public int LPad {
get {return iLPad;}
set {iLPad = value;}
}
&n