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. 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 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> | DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More ASP.NET Code Articles More By aspfree developerWorks - FREE Tools! | Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base. FREE! Go There Now!
| | | | Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise. FREE! Go There Now!
| | | | Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications. FREE! Go There Now!
| | | | Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today. FREE! Go There Now!
| | | | As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br /> FREE! Go There Now!
| | | | Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository. FREE! Go There Now!
| | | | Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users. FREE! Go There Now!
| | | | Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time. FREE! Go There Now!
| | | | The Eclipse community is constantly working to extend Eclipse's functionality. In this webcast, learn about some of the most important and feature-rich projects under development. From multi-language support to plug-in development, tune in to see what Eclipse is capable of now. FREE! Go There Now!
| | | | Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise. FREE! Go There Now!
| | | | All FREE IBM® developerWorks Tools! | |