Form code generator V1.1 by Steve Schofield[bate2 等级:中级](转载:aspfree)

This article revolves around being plain lazy. When it comes to creating Form code based on some  database table, I hate it! This code sample goes along way in speeding this process up for me.   There still is some manual parts to finish up the form code but this takes care of remembering what columns are in the database table.    In future releases, we'll provide more functionality to further automate this but this is a big first step in my opinion!  The following four steps listed below can be followed and this will generate the ASP.NET code. A big thanks to Dave W. Webmaster of  for saving me on many things!!

Define what database you want to connect to in the config.web.  This is stored in the connection string
<configuration>
    <appsettings>
        <add key="dsn" value="server=localhost;uid=sa;pwd=;database=aspfree" />
    </appsettings>
</configuration>
Load the aspx page in your browser, select the table to create the Form code from
Select the checkboxs of which fields to be on the form
Copy and paste into your code..
Here is a screen shot of the File after following the above steps.

Here is the code:

<%@ Page Language="VB" EnableSessionState="False" EnableViewState="True" Trace="False" Debug="False" Strict="True" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="VB" runat="server">
Dim sqlText as String
Dim ds as New DataSet
Dim dbComm AS New SQLDataAdapter
Dim conn AS SQLConnection
Dim sqlServer as String

Sub Page_Load(sender As Object, e As EventArgs)

          SQLserver = GetSqlConn()
          conn = New SQLConnection(SQLserver)

          If Not IsPostBack then
                    sqlText = "select id, name from sysobjects where xtype='U' order by name"
                    dbComm = New SQLDataAdapter(sqlText,conn)
          dbComm.Fill(ds,"AllTables")
          tblList.DataSource = ds.Tables("AllTables").DefaultView
          tblList.DataTextField = "name"
          tblList.DataValueField = "name"
          tblList.DataBind()
End if

End Sub

Function CreateValidator(myName as string) as String
          Dim mySB as StringBuilder = New StringBuilder()

          REM -- use :<some text>: as placeholders
          mySB.Append ("<asp:RequiredFieldValidator runat=""server"" id="":Name:"" ControlToValidate="":control:"" ErrorMessage="":errMsg:"" display=""Static"">This Required Field!</asp:RequiredFieldValidator>" )

          mySb.Replace(":Name:","vld" & myName) 'add the validator name
          mySb.Replace(":control:","at" & myName) 'add the control name
          mySb.Replace(":errMsg:",myName & " is required")

Return mySb.ToString()

End Function

Function GetSqlConn() as String
          Dim DSN as String = ConfigurationSettings.AppSettings("DSN")
          Return DSN
End Function

Sub GetTable_Click(sender As Object, e As EventArgs)
          Dim sqlText as String
          sqlText = "SELECT syscolumns.name, syscolumns.isnullable FROM sysobjects INNER JOIN syscolumns ON sysobjects.id = syscolumns.id where sysobjects.name = '" & tblList.SelectedItem.Text & "' ORDER BY syscolumns.colid"

REM -- Connect to SQL
          dbComm = New SQLDataAdapter(sqlText,conn)

REM -- Fill DataSet
          dbComm.Fill(ds,"TestData")
          MyDataGrid.DataSource = ds.Tables("TestData").DefaultView
          MyDataGrid.DataBind()

REM -- Show the results
          myPanel.Visible= True

End Sub

Sub Button1_Click(sender As Object, e As EventArgs)

          Dim i As Integer
          Dim _item As DataGridItem
          Dim dr As DataRow
          Dim sb as StringBuilder = New StringBuilder()
          Dim strOutput as String

REM -- Auto Generate The Form
          sb.Append( "<form runat=""server"" id=""form2"" name=""form2"">" & Chr(13) & Chr(10) )
          sb.Append( " <table border=1>" & chr(13))

          For i = 0 To MyDataGrid.Items.Count - 1
REM -- Get the checkbox
          _item = MyDataGrid.Items(i)
          Dim addCheckBox As CheckBox = Ctype(_item.FindControl("chkAdd"),CheckBox)
          Dim validCheckBox as CheckBox = Ctype(_item.FindControl("chkValid"),CheckBox)

                    If addCheckBox.Checked then
                              sb.Append( " <tr>" & chr(13))
                              sb.Append( " <td>" & _item.Cells(1).Text & "</td>" & chr(13))
                              sb.Append( " <td>")
                              sb.Append( "<asp:textbox id=""at" & _item.Cells(1).Text & """ runat=""server"" />" )

                              'create a validator control
                              If validCheckBox.Checked then
                                        sb.Append (" " & chr(13) & CreateValidator(_item.Cells(1).Text ) )
                              End if

                              sb.Append ("</td>" & chr(13)) '
                              sb.Append ( " </tr>" & chr(13)) ' close out the row
                    End if

Next
          sb.Append ( " <tr>" & chr(13)) ' close out the row
          sb.Append(" <td colspan=""2""><asp:button id=""button1"" Text=""Validate Form"" runat=""Server"" /></td>" & chr(13))
          sb.Append ( " </tr>" & chr(13)) ' close out the row
          sb.Append ( " </table>" & chr(13) )
          sb.Append(chr(13) & "</form>")
          strOutput = sb.ToString()
          strOutput = System.Web.HttpUtility.HTMLEncode(strOutput)
          taResults.Value = strOutput
          pnlTextarea.Visible=True
End Sub

</script>

<html>
<head>
<title></title>
</head>
<body bgcolor="#FFFFFF" >
          <form runat="server" id=form1>
                    Select a tablename to create a .NET form for:
                              <asp:dropdownlist id="tblList" runat="server"/>  
<asp:Button id=GetTable Text="Get Table" onclick="GetTable_Click" runat="server" />

<asp:panel id=myPanel runat="server" visible="false">
<br>
Select the Columns used for generating the form.

<asp:datagrid id=MyDataGrid runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
AutoGenerateColumns="False"
>
<Columns>
<asp:TemplateColumn HeaderText="Add?">
<ItemTemplate>
<center>
<asp:CheckBox id=chkAdd runat="server" />
</center>
</Itemtemplate>
</asp:TemplateColumn>

<asp:BoundColumn HeaderText="Name" DataField="name"/>

<asp:TemplateColumn HeaderText="Create Validator?">
<ItemTemplate>
<center>
<asp:CheckBox id=chkValid runat="server" />
</center>
</Itemtemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>

<asp:Button id=Button1 Text="Create Form" onclick="Button1_Click" runat="server" />
</asp:panel>

<asp:panel id="pnlTextarea" visible="false" runat="server">
<p>Copy this code into a new ASP.NET page</p>
<textarea id=taResults cols=90 rows=40 runat="server" />
</asp:panel>

</form>
</body>
</html>

时间: 2024-09-30 21:27:02

Form code generator V1.1 by Steve Schofield[bate2 等级:中级](转载:aspfree)的相关文章

Form code generator V1.1 by Steve Schofield[bate2

This article revolves around being plain lazy. When it comes to creating Form code based on some  database table, I hate it! This code sample goes along way in speeding this process up for me.   There still is some manual parts to finish up the form

NCC Tools(never code counter tools) V1.0.1发布代码-代码统计工具_hta

界面如下图:把源代码存为(hta)文件,因为hta文件没有状态栏,所以我这里建议大家存为html文件,这样可以在状态栏下看到 NCC扫描的进度,我这里把NCC的maxloop设置为3000,所以文件统计到3000的时候,会自动终止,以防文件夹中文件太多造成运行的负担. 如果大家喜欢这样的代码,就请关注"Never Modules" 主要功能有- 1.可自己选择文件夹,或者单个文件. 2.自己选择文件后缀名进行统计 3.output information输出的数据有: 文件个数, 文件

C++:随机数生成器(random-number generator) 详解

随机数, C语言的函数是rand(), C++则是随机数生成器(random-number generator) = 分布对象(distribution object) + 引擎(engine); 使函数每次生成不同的随机数, 需要使用静态(static)局部变量, 这样分布对象和引擎就能保持(hold)状态(state), 每次都生成一个新的; 生成随机的整数, 使用分布对象uniform_int_distribution<>, 默认模板参数是int; 生成随机的浮点数, 使用分布对象uni

Path to a Trusted Front-end Code Protection

Introduction As an appealing objective in the information security field, a trusted system refers to a system that achieves a certain degree of trustworthiness by implementing specific security policies. For computers, the Trusted Platform Module (TP

[转]T4 Code Generation

[原文:http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx]Rob beat me to it. Blogging about T4 (the Text Template Transformation Toolkit) had been on my list literally for a year. He and I were

myeclipse2014 struts 2.2.1 下s:form显示问题

问题描述 <%@pagelanguage="java"import="java.util.*"pageEncoding="ISO-8859-1"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServ

linux-Centos 6.6线面安装LoadRunner Generator for Linux.part

问题描述 Centos 6.6线面安装LoadRunner Generator for Linux.part 运行安装脚本installer.sh 错误如下: [root@localhost Linux]# ./installer.sh INCLUDE function requires 1 parameter 解决方案 http://download.csdn.net/detail/h101617193/7140359 解决方案二: Using SQLMetal code generator

090723 T Code Generate 的思考

今天看了公司(易车)原来团队开发的部分项目的代码,发现很多项目是基于Typed DataSet或NetTiers的,两者都是代码生成器(Code Generator,以下简称CG),前者是VS自带的工具,而后者则是第三方开发,同样的还有CodeSmith.动软等.这些CG的输入/信息来源,大都是数据库中的元数据. 其实,我个人也开发过CG.第一个是在上海外高桥实习时用于转换C语言到C#语言的转换器.另一个则是配合hxy.LayersFramework框架的生成器,其输入主要来自于LINQTOSQ

Python中使用django form表单验证的方法

一. django form表单验证引入 有时时候我们需要使用get,post,put等方式在前台HTML页面提交一些数据到后台处理例 ; <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form</title> </head> <body> <div> <for