Welcome to Dream.In.Code
Become a C# Expert!

Join 137,199 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,326 people online right now. Registration is fast and FREE... Join Now!




Custom Server Controls

 
Reply to this topicStart new topic

> Custom Server Controls, how to create a basic custom server control

rgfirefly24
Group Icon



post 17 Jun, 2008 - 11:51 AM
Post #1


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:

CODE

<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:

CODE

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
CODE

[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

CODE

[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

CODE

public class WebCustomControl1 : WebControl


to read
CODE

public class WebCustomControl1 : DropDownList


below that you see a group of declerations:

CODE

[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.microsoft.com/en-us/library/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

CODE

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.

CODE

//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

CODE

        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()

CODE

         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.

CODE

//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
CODE

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YearDropDownListTest._Default" %>


create a blank space under it and enter
CODE

<%@ 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 smile.gif

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: 112
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 12/4/08 12:20PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month