Custom Controls in Asp.Net

In this article I will explain about how to build custom controls in ASP.NET.

Custom Control means creating our own control with our own functionality (based on our requirement).

In .Net Framework Microsoft provided many controls like Textbox, Label, Gridview, Repeater, and DropDownList…etc. They all are fulfilling most of our requirements.

But in some situations we need some more functionality to be performed by controls and in some easy way.

For example we need some control to ask the users to fill there address. For that we can take textarea (textbox will act as a textarea when it is textmode is equal to Multiline) with some validations. For this generally we can use some validation controls to validate. But if we want to use Address textarea in several pages of our site, then we need to implement all validations at each and every use of textarea.

Instead of that we can implement all validations for textarea at one place and we can use this as a single control where ever we want as a custom control.

Here I explained about super gridview control which we will take connectionstring and SQL query to fill itself with out use of any other control or object.

Here I consider database as SQL Server 2005.

Generally we bind data to Gridview control through Dataset or SqlDataSource(that means by using of some other control or object).

Instead of that we can develop one control, which we will take connection string and SQL Query to bind data by it’s own.

Creating Super Gridview CustomControl:

Here I explained all code in VB.NET only. You can convert this code into C# easily.

To develop Custom control is easy.

Open Visual studio Tool File-> New -> Project

Then select Class Library in the right side panel, mention folder name and Press Ok
And change class name to SuperGridview.

Before proceeding into the code, add reference to System.Web. Right click on Solution Explorer and select Add Reference System.Web, press ok.

Import five namspaces into our code. Those are System.Web, System.Web.UI, System.Web.UI.Webcontrols, System.Data and System.Data.SqlClient.

The code to create custom gridview control look like this.

 
Imports System.Data Imports System.Data.SqlClient Imports System.Web.UI Imports System.Web.UI.WebControls Public Class SuperGridview Inherits WebControl Protected lbl1 As Label Protected gv1 As GridView Dim query As String, con_string As String Public Property strsql() As String Get Return query End Get Set(ByVal value As String) query = value End Set End Property Public Property connectionString() As String Get Return con_string End Get Set(ByVal value As String) con_string = value End Set End Property Protected Overrides Sub CreateChildControls() lbl1 = New Label lbl1.ID = "lbl1" Me.Controls.Add(lbl1) gv1 = New GridView gv1.ID = "gv1" Me.Controls.Add(gv1) End Sub Protected Overrides Sub RenderContents(ByVal writer As System.Web.UI.HtmlTextWriter) Try Dim sqldad As SqlDataAdapter, ds As New DataSet Dim con As New SqlConnection(con_string) If String.IsNullOrEmpty(strsql) = False And String.IsNullOrEmpty(con_string) = False Then sqldad = New SqlDataAdapter(strsql, con) sqldad.Fill(ds) gv1.DataSource = ds.Tables(0) gv1.DataBind() End If gv1.RenderControl(writer) Catch ex As Exception lbl1.Text = ex.Message Finally lbl1.RenderControl(writer) End Try End Sub End Class

In the above code you can observe I took the Public Properties, one for connection string(connectionString) and another for SQL query(strsql).
Here you need to inherit Webcontrol class and you need to override CreateChildControls and RenderContents methods.

CreateChildControls class is to create basic controls and RenderContents for to render the controls to Browser.

To change control prefix, you need to register this control in AssemblyInfo.vb class. You can find this class under My Project Open AssemblyInfo.vb class and mention tageprefix for the control based on namespace.

        <Assembly: system.Web.UI.TagPrefix("Custom_Control", "CustomControl")>



Here I mention control prefix as CustomControl for Custom_Control namespace.

Build the project. For that Right click on SolutionExplorer and select Build option. Now your code is compiled into DLL file and your control is ready to use.

In this way you can create any custom control with your own functionality based on your requirements.

Use SuperGridview Custom Control:

After creating custom control based on your requirement, you can easily integrate that control in your application.

There are several ways to integrate custom controls into your application. Here I used the one way by adding the control to Toolbox.

Open ToolBox, on General Tab Right click and select Choose Items. Browse to our custom control DLL file and add that dll file to our ToolBox.

Now the Control is added to our ToolBox. You can Drag and drop that control to source code.
Using the Custom control code look like below.

 
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <%@ Register Assembly="Custom_Control" Namespace="Custom_Control" TagPrefix="CustomControl" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <CustomControl:SuperGridview strsql="select * from emp1 with (nolock)" connectionString="server=(local);uid=sa;pwd=dlog24;Database=Employee;" ID="SuperGridview1" runat="server" /> </div> </form> </body> </html>

In the above code you can observe Tageprefix as CustomControl( we mentioned it in AssemblyInfo class of CustomControl).

By mentioning values connectionString as Connection string for Database and strsql as SQL query, you can bind the Data to Gridview.

In this way you can Create and use your own controls based on your Requirements.

You can find source code for Create Custom Control and how to use custom control in our application below.


To Create Custom Control Download source code here

To Use Custom Control Download source code here