Click here to Skip to main content
15,903,012 members
Articles / Web Development / ASP.NET

ASP.NET Webform Generator

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
5 Apr 2015CPOL1 min read 26.9K   19   5
When supplied with a connection string and table name, this tool will read the field data types and create asp controls for you to copy and paste in your own project.


Many times I've found myself recreating similar web forms for various projects.  Even copying and pasting my old code to a new project required modifications.  So being the lazy person I am with some free time one evening I decided to code a little tool to help with that.  You supply a connection string and a table name, and it will generate asp controls based on that table and the data types.

It also generates asp labels based on the column name and associates them to the corresponding textboxes, textarea, checkboxes etc...  The other nifty feature I wanted to put in was support for JQuery's datepicker.  If a datetime field type is found in the database, a textbox with corresponding label will be created (just like any other varchar datatype) but this will also generate the necessary javascript required for the datepicker.


Using the code

Pretty easy to impliment.  Make sure you have a reference to the JQuery library. (I used version 1.5 in my project but it should work just fine with newer versions as well)

Place this on your page in the javascript section. (You don't really need the error checking part, but I put it in there anyway.)

function ErrorCheck()
            $("#<%=txtASPCode.ClientID %>").val("");
            $("#<%=txtJquery.ClientID %>").val("");

            if ($("#<%=txtConnString.ClientID %>").val() == "")
                alert("Connection string can not be blank.");
                return false;
                return true;
        function TrimAllTextboxes()
            $("input[type=text], textarea").each(
            function ()

And copy/paste this code in the form tag:

<asp:Label ID="lblConString" runat="server" Text="Connection String"></asp:Label>:
<asp:TextBox ID="txtConnString" runat="server" style="width:600px"></asp:TextBox><br />        
<asp:Label ID="lblTableName" runat="server" Text="Table Name (Optional)"></asp:Label>:
<asp:TextBox ID="txtTableName" runat="server" style="width:300px"></asp:TextBox><br />
<asp:Label ID="lblDatePickerOptions" runat="server" Text="JQuery Datepicker Options (Optional)"></asp:Label>:
<asp:TextBox ID="txtJQueryDatepickerOptions" runat="server" style="width:300px"></asp:TextBox><br />
<asp:Button ID="btnGenerate" runat="server" Text="Generate!" OnClientClick="ErrorCheck();" CausesValidation="true" /><br /><br/>
<h1>ASP Code:</h1>
<asp:TextBox ID="txtASPCode" runat="server" TextMode="MultiLine" Rows="20" style="width:100%"></asp:TextBox>
<h1>JQuery Code:</h1>
<asp:TextBox ID="txtJquery" runat="server" TextMode="MultiLine" Rows="20" style="width:100%"></asp:TextBox>

And in the code behind, there's a couple imports:

Imports System.Data.SqlClient
Imports System.Data

And the rest of the code is in the btnGenerate.Click

            Dim Script As New StringBuilder
            Script.Append("SELECT table_name, column_name,data_type,character_maximum_length,column_default FROM information_schema.columns where table_name not like '%aspnet_%' and table_name not in( 'sysdiagrams') ")

            'if they specified a table name, filter by that
            If Not String.IsNullOrEmpty(Me.txtTableName.Text) Then
                Script.AppendFormat(" and table_name='{0}' ", Me.txtTableName.Text)
            End If

            Script.Append("ORDER BY table_name, ordinal_position")
            Dim ASPCode As New StringBuilder
            Dim JQueryCode As New StringBuilder
            Using SelectCommand As New SqlCommand
                With SelectCommand
                    .Connection = New SqlConnection(Me.txtConnString.Text)
                    .CommandType = CommandType.Text
                    .CommandText = Script.ToString
                    Using dr As SqlDataReader = .ExecuteReader
                        While dr.Read
                            Dim TableName As String = dr("table_name")
                            Dim DataType As String = dr("data_type").tolower
                            Dim DataLength As String = IIf(dr("character_maximum_length") Is DBNull.Value, "", dr("character_maximum_length"))
                            Dim ColumnName As String = dr("column_name")
                            Dim ColumnDefault As String = IIf(dr("column_default") Is DBNull.Value, "", dr("column_default")).ToString.TrimStart("(").TrimEnd(")").TrimStart("'").TrimEnd("'")
                            Dim AssociatedControlPrefix = ""
                            Dim Control As String = ""

                            'only show the table name if it isn't already shown
                            If Not ASPCode.ToString.Contains(String.Format("<h1>{0}</h1>", TableName)) Then
                                ASPCode.AppendFormat("<h1>{0}</h1>{1}", TableName, Environment.NewLine)
                            End If

                            'doing this with if instead of case as there are several date type of data types
                            If DataType = "bit" Then
                                'asp checkbox
                                AssociatedControlPrefix = "chkBox"
                                Control = String.Format("<asp:CheckBox ID=""{0}{1}"" Checked=""{2}"" runat=""server"" />", AssociatedControlPrefix, ColumnName, IIf(ColumnDefault = "((1))", "true", "false")) 'if the default value isn't null then set the checked equal to the default value
                            ElseIf DataType.Contains("date") Then
                                'textbox with jquery to bind as date picker
                                AssociatedControlPrefix = "txt"
                                Control = String.Format("<asp:TextBox ID=""{0}{1}"" runat=""server""></asp:TextBox>", AssociatedControlPrefix, ColumnName)
                                JQueryCode.AppendFormat("$(""#<%={0}{1}.ClientID%>"").datepicker({2});{3}", AssociatedControlPrefix, ColumnName, Me.txtJQueryDatepickerOptions.Text, Environment.NewLine)
                                AssociatedControlPrefix = "txt"
                                If String.IsNullOrEmpty(DataLength) OrElse Not IsNumeric(DataLength) Then
                                    'no max length
                                    Control = String.Format("<asp:TextBox ID=""{0}{1}"" runat=""server"">{2}</asp:TextBox>", AssociatedControlPrefix, ColumnName, ColumnDefault)
                                    'varchar(max) or blob or ntexts etc
                                    If (DataLength = -1 AndAlso DataType = "varchar") OrElse DataType = "ntext" OrElse DataType = "text" Then
                                        Control = String.Format("<asp:TextBox ID=""{0}{1}"" runat=""server"" TextMode=""MultiLine"">{2}</asp:TextBox>", AssociatedControlPrefix, ColumnName, ColumnDefault)
                                        'textbox with a max length for everything else
                                        Control = String.Format("<asp:TextBox ID=""{0}{1}"" runat=""server"" MaxLength=""{2}"">{3}</asp:TextBox>", AssociatedControlPrefix, ColumnName, DataLength, ColumnDefault)
                                    End If
                                End If
                            End If
                            Dim Label As String = String.Format("<asp:Label ID=""lbl{0}"" runat=""server"" Text=""{1}"" AssociatedControlID=""{2}{3}""></asp:Label>", ColumnName, ColumnName, AssociatedControlPrefix, ColumnName)

                            ASPCode.AppendFormat("{0}:{1}<br/>{2}", Label, Control, Environment.NewLine)                           
                        End While
                    End Using
                End With
                Me.txtASPCode.Text = ASPCode.ToString
                If Not String.IsNullOrEmpty(JQueryCode.ToString) Then
                    Me.txtJquery.Text = String.Format("<script language=""javascript"" type=""text/javascript"">{0}$(document).ready(function(){{{0}{1}}});{0}</script>", Environment.NewLine, JQueryCode.ToString)
                End If
            End Using
        Catch ex As Exception
        End Try


Points of Interest

I jokingly tell my friends that coders are (generally) lazy people, but that they also come up with useful tools to save time in the end.  That's basically where the idea for this little project came from. 

I hope you find it helpful and cuts down some development time for you. :)


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Web Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

GeneralMy vote of 5 Pin
bhavin.ember14-Apr-15 10:06
bhavin.ember14-Apr-15 10:06 
QuestionBind Pin
david4life6-Apr-15 11:05
david4life6-Apr-15 11:05 
GeneralThanks, Big help, time saver. Pin
Brian Stevens6-Apr-15 10:05
Brian Stevens6-Apr-15 10:05 
GeneralNice Tool. Love it. Pin
Kaushik S Murthy6-Apr-15 2:21
Kaushik S Murthy6-Apr-15 2:21 
QuestionExcellent Article! Pin
Your Display Name Here6-Apr-15 0:14
Your Display Name Here6-Apr-15 0:14 
I don't think it's laziness at all, rather you are getting to more abstract ways of doing things which is better all around. The concept of self generating forms is a great idea! Thanks for posting this.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.