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! | <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts. FREE! Go There Now!
| | | | Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time. FREE! Go There Now!
| | | | Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations. FREE! Go There Now!
| | | | Visit IBM developerWorks to download a free trial version of Lotus Quickr 8.0, which enables collaboration by transforming the way everyday business content such as documents, rich media, photos, and video can be shared. Lotus Quickr makes it faster and easier to share content of all types (not just documents) within virtual teams. It is designed to make it easier to collaborate across organizational boundaries, while continuing to work within the context of familiar desktop applications. FREE! Go There Now!
| | | | Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms. FREE! Go There Now!
| | | | Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1. FREE! Go There Now!
| | | | Get a free trial download of the latest version of IBM Rational Method Composer V7.2 which helps you deliver customized yet consistent process guidance to your project teams and IT organization, and includes the latest version of IBM Rational Unified Process (RUP), which has provided process guidance to teams since 1996. FREE! Go There Now!
| | | | IBM Lotus Notes 8 provides a wide range of developers the ability to provide customized, integrated user interfaces via composite applications and via custom sidebar and toolbar plug-ins. This webcast provides you with tips and techniques to use with out-of-the-box capabilities of Lotus Notes 8, and survey how you can share useful components within your own company and within a larger community. 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!
| | | | With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential. FREE! Go There Now!
| | | | All FREE IBM® developerWorks Tools! | |