Reduce Repetitive Code with ASP.NET Custom Controls - Creating the Control (Page 2 of 6 )
Imagine that you are writing an ASP.NET application to manage contact information. One control that would be useful in such an application would be a standard "Contacts" dropdown.
For this example, assume that you have a Contact class with properties such as Contact ID, First Name, Last Name, Address, City, State and ZIP.
The Contact class also has a read-only property called Name that returns a concatenation of Last Name comma First Name.
Additionally, you have a Contacts class that inherits from the CollectionBase class and holds a collection of Contact objects.
To create your custom Contacts web control, first create a class called ContactsDropDownList that inherits from the DropDownList class.
You’ll need to create the following properties as well:
Name
Type
Description
SelectedContactID
Int32
Read-only. Returns the selected Contact ID.
SelectedContactName
String
Read-only.Returns the selected Contact Name.
AutoLoadData
Boolean
Determines whether the control should perform its own data access. If false, then the DataSource must be supplied by the developer.
The C# code for the class with the properties defined is shown below.
using System; using System.Web; using System.Web.UI.WebControls;
namespace WebControls { public class ContactsDropDownList : DropDownList { private bool _autoLoadData = true; public bool AutoLoadData { get { return _autoLoadData; } set { _autoLoadData = value; } }
public int SelectedContactID { get { return int.Parse(this.SelectedItem.Value); } }
public string SelectedContactName { get { return this.SelectedItem.Text; } } } }
This class will also need a constructor, and in the constructor you can set the properties of the base class so that every instance of this control will have the same look and feel.
By setting display properties in the constructor, you also allow a developer to change these values when they declare the control in an ASP.NET page.
Use the code below to set the CssClass and Width properties:
public ContactsDropDownList() { base.CssClass = "text-default"; base.Width = new System.Web.UI.WebControls.Unit(250); }