Page 1 of 1

Custom Server Controls how to create a basic custom server control

#1 rgfirefly24  Icon User is offline

  • D.I.C Lover
  • member icon


Reputation: 267
  • View blog
  • Posts: 1,470
  • Joined: 07-April 08

Posted 17 June 2008 - 12:51 PM

Today we will be looking at something that all programers would love to know, but few can master. In this tutorial i will go over some basic parts of
a Custom Server control and I will also show you how to set up your own custom Drop Down List control.

We will be using Visual Studio 2005 to build this control.

Lets start off at looking at what a Server Control is. A Server Control is something like a textbox or label that either gathers data or displays data
server side.

The basic setup of a Server control looks like this:

<asp:DropDownList ID="DropDownList1" runat="server" />



lets break down that tag

<asp: this part is the tag prefix that was defined in your register tag. It points to a certain assembly, and namespace.

:DropDownList this part defines the Control itself. Later i will show you where this comes from.

ID="DropDownList1" this defines the identity of this instance of the control. It will be used throughout your code to define this instance.

runat="server" this tells the aspx page that the control that is being rendered is handled by serverside code.

/> closes the tag. Just like in HTML all your asp items need a closing tag.

ok now that we know the basic layout of an asp control tag, how are we going to create our own?

Well to do this Simply open up Visual Studio 2005 >> File >> new Project >> other languages >>
visual c#(you can do this in VB aswell, but for this tutorial i'll be using C#) >> Windows >> Web Control Library.

after selecting Web Control Library you will want to give it a good descriptive name. For this tutorial lets call it YearDropDownList.

after you click ok you will see a .cs file open called WebCustomControl1.cs in that file it contains the basic setup for creating a custom control:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace YearDropDownList
{
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
	public class WebCustomControl1 : WebControl
	{
		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		[Localizable(true)]
		public string Text
		{
			get
			{
				String s = (String)ViewState["Text"];
				return ((s == null) ? String.Empty : s);
			}

			set
			{
				ViewState["Text"] = value;
			}
		}

		protected override void RenderContents(HtmlTextWriter output)
		{
			output.Write(Text);
		}
	}
}



notice this part
[ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]



this is whats going to define the control in the toolbox. Lets go ahead and change that to say YearDropDownList

[ToolboxData("<{0}:YearDropDownList runat=server></{0}:YearDropDownList>")]



while we are at it lets change the name of the .cs file to YearDropDownList.cs

you will also notice that this class extends WebControl. WebControl is the base class that houses all the properties for a control. I.E height, width, fonts, etc.

for this tutorial we will go ahead and extend of a already defined control DropDownList. So change the line

public class WebCustomControl1 : WebControl



to read
public class WebCustomControl1 : DropDownList



below that you see a group of declerations:

[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		[Localizable(true)]



these tell about the program.

Bindable: specifies for visual designers whether it is meaningful to bind the property to data

Category: specifies how to categorize the property in the visual designer's property browser

DefaultValue: specifies a default value for the property

Localizable: specified as true or false, specifies for visual designers whether it is meaningful to localize the property.

(definitions obtains from : http://msdn.microsof...y/yhzc935f.aspx )

one that isnt shown here is Description. Description Allows you to set a description that will be shown at the bottom of the properties window
when a user selects that property.


next we have

public string Text
		{
			get
			{
				String s = (String)ViewState["Text"];
				return ((s == null) ? String.Empty : s);
			}

			set
			{
				ViewState["Text"] = value;
			}
		}
		


The above code is called a property. Properties define the look and feel of a server control. You can create any property you want as long as you
apply it to your rendered control properly.
The text property will not be needed so go ahead and remove that.
instead lets go ahead and enter a property in called startyear.

 //define the get and set methods for storing and retrieving the start year
		
		protected int _StartYear;
		public int StartYear
		{
			get
			{
				return _StartYear;
			}
			set
			{
				_StartYear = value;//Setting startyear to value allows the user to input an int value and store it in startyear.
			}
		}
		


after we get done defining the start year lets go ahead and define a property for the endyear

		protected int _EndYear;
		 public int EndYear
		 {
			 get
			 {
				 return _EndYear;
			 }
			 set
			 {
				 _EndYear = value;
			 }
		}
		


now we have defined two properties, start year and end year. What to do now. Well thats relativly simple. We want to populate the dropdownlist will all
years between _StartYear and _EndYear to do this we create a method called PopulateDropDown()

		 private void populatedropdown()
		{
			//notice we use the property names instead of the variable names.
			for (int i = this.StartYear; i <= this.EndYear; i++)
			{
				//adds the specified year				
				this.Items.Add(new ListItem(i.ToString(), i.ToString()));

			}
		}
   



So if the startyear was set to 2005 and the endyear was set to 2010 it would add all the years starting at 2005 and going through 2010.

next we need to call populatedropdown() from somewhere. We will go ahead and do this in the OnPreRender method.

//notice that the OnPrePrender method already exsists so we will be overriding it
 protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			populatedropdown();
		}




Now we have that done. Lets go ahead and remove the RenderContents method. We dont use that so lets not keep it in the program.

ok, We are done building the actual control now lets move on to how to impliment it.

Go ahead and click on Solution 'YearDropDownList' then go file >> add >> new Project >> other languages >>
visual c# >> Web >> ASP.Net Web Application.

Lets name this one YearDropDownListTest.

ok once that loads up right click on the Project YearDropDownListTest and select Set as Startup Project.

next right click on References and select Add Reference. Once that window pops up select projects, click on YearDropDownList and click ok.

this adds the reference to the custom control you created. Now we'll go ahead and add a register tag in our default so we can use it.

double click the Default.asp page, if it doesnt take you straight to source view, go to sourceview.

At the top where you see
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YearDropDownListTest._Default" %>



create a blank space under it and enter
<%@ Register Assembly="YearDropDownList" Namespace="YearDropDownList" TagPrefix="CDDL" %>



this will register the custom control.

Now go ahead back to Design view and check your toolbox. Notice that your control is there? Now drag and drop it to the page and use it like
a normal control :)

hope this tutorial helps you in understanding the basics of custom controls. Look for my next tutorial on creating A custom control that uses mutliple controls.

complete project here:

Attached File  YearDropDownList.zip (46.26K)
Number of downloads: 1182

Is This A Good Question/Topic? 0
  • +

Replies To: Custom Server Controls

#2 rhul_k  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 17-September 09

Posted 18 September 2009 - 03:45 AM

Very good post... Thanks for sharing this.

This post has been edited by rhul_k: 18 September 2009 - 03:50 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1