Wednesday, July 27, 2011

Visual Studio .NET Web Custom Control

There are a few articles out there explain how to develop your own web custom control by deriving from base control class, and customize the control with all the basic functionality of server control. Here is one useful link from Microsoft MSDN that give you a walkthrough showing you how to do it.

The Microsoft MSDN article show you how to use custom server control from different projects by adding the project with custom control as a reference (the .DLL file) to your main project. If you want to create the custom control class in the same project, you could map the control in a page or in the web.config file.

For tag prefix @Register declaration in a page,

<%@ Register Assembly="YourProjectName" TagPrefix="YourCustomTage (e.g. aspSample)" Namespace="YourCustomServerControlName"%>

For example,

<%@ Register Assembly="ServerControl" TagPrefix="aspSample" Namespace="CustomListBox"%>

Alternatively, you could specify the tag prefix/namespace mapping in web.config file,

<?xml version="1.0"?>
 <configuration>
   <system.web>
    <pages>
      <controls>
        <add tagPrefix="aspSample" Assembly="ServerControl"
          namespace="ServerControl">
        </add>
      </controls>
    </pages>
   </system.web>
 </configuration>

Notes: Remember the assembly would be your project name or the DLL (if custom control is from different project)

In addition, if you want to be able to drag the custom control from the tool box, you could add the custom control project (or same project has the custom control class) in the reference. But before you do that, you could customize the tag prefix. To do that, add an Assembly: TagPrefix attribute in the project AssemblyInfo file.

Open the AssemblyInfo file, Add these codes in the AssemblyInfo page,

' Visual Basic
 Imports System.Web.UI

<Assembly: TagPrefix("CustomListBox", "aspSample")>

//C#
 Using System.Web.UI;

[assembly: TagPrefix("CustomListBox", "aspSample")]

Have fun coding!

No comments:

Post a Comment