InsertItemTemplate FormView Example in ASP.NET 3.5

Inserting records into an MS SQL Server database from an ASP.NET 3.5 web page is often necessary; therefore, it's important for many web applications to be able to do this. This article will walk you through creating a real application that can take information from a form built in ASP.NET and put it into an MS SQL Server database.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 10
June 02, 2010
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

For example, suppose you want to build a web application that will ask the user for three pieces of information:

a. Profile Name

b. Profile Age

c. Email Address

And after applying input validation techniques, the user's information will be saved in the database.

It would also be important to be able to retrieve all records and put them in a GridView, so that any user will know that his/her submitted information has been received.

In this tutorial, we will use an editable formview web control to create this application. It should like the screen shot below (FormView is used to gather user inputs and the GridView web control is used to retrieve records):

Create the database

After creating the project in Visual Web Developer Express, you need to create the database with the following details:

Database name: profiles.mdf

Table name: profiletable

Fields:

Primary Key Index: profileid

Refer to this complete guide on creating MS SQL server database in ASP.NET 3.5 using Visual Web Developer: http://www.aspfree.com/c/a/ASP.NET/Creating-an-ASPNET-Database-using-MS-SQL-2008-in-Visual-Web-Developer-2008/

Do not worry that the table won’t have any data at first, because it will be inserted later on in this tutorial.

Basic Controls in Default.aspx

Once you have created and added the database, the Default.aspx does not have controls to gather user inputs and retrieve database records.

In the Default.aspx source code, let’s start dragging SqlDataSource from View à Toolbox à Data (place it between <div> tags); you can configure it in the Design view by right clicking on it and then clicking Show Smart Tag à Configure Data Source. Configure it according to the following (by order):

Data Connection used to connect to the database: profiles.mdf

Check “Yes, save this connection as: ConnectionString”

Under “How would you like to retrieve data from your database?”:

Name of the table: profiletable

Columns: *

Then click “Advanced” à check “Generate INSERT, UPDATE, and DELETE statements” and click OK.

Finally, to complete the SqlDataSource configuration, click Next and Finish.

Next, drag the FormView web control from View à Toolbox à Data and put it next to SqlDataSource. Right click on it in the Design view and click “Show Smart Tag,” and then, under “Choose Data Source,” select “SqlDataSource1.”

The rest of the configuration needs a more detailed discussion.

Configuring FormView to Accept Data Insertion

Based on the earlier screen shot, you need FormView to accept user inputs. To do this, right click on the FormView web control in the Design view, and click Properties.

Under “Behavior,” change DefaultMode from “ReadOnly” to “Insert.” This is very important; it will let FormView accept user inputs by default when viewed in the browser.

Let’s improve the appearance of the web form. In FormView, since you are using it to insert records into the database, the appropriate template is InsertItemTemplate.

Formview can be customized through seven different templates; three of them are the most important:

a. ItemTemplate. Use this one if you are using FormView to retrieve records from a database.

b. EditItemTemplate. This is the one to use if you are using FormView to update records to the database.

c. InsertItemTemplate. Use this one if you are using FormView to insert records into the database.

In this project example, just ignore the other templates; we'll focus on configuring InsertItemTemplate.

In fact, you only need to customize InsertItemTemplate for your web form to look better.

Right click on FormView in the Design view, click “Show Smart Tag” and then click the “Edit Templates” link. Under “Display,” select “InsertItemTemplate”:

Start by editing the following:

1. Change the default profilename to “Enter your name.” Do the same for age by replacing the text with “Enter your age:” and email for “Enter your email:”

2. Remove the “Cancel” because it is not needed. Select and hit the delete key in your keyboard.

3. You can adjust the width of the text box to make it look wider. Use the following:

a. name and email = textbox width = 192 px

b. age textbox width = 49 px

You can adjust the width by selecting the textbox web control in Design, and then clicking “Source” to go to Source code view; after that, add a Width property (see below):

Width="192px" 

After adding the property, it will look like this:

 

<asp:TextBox ID="profilenameTextBox" width="192px" runat="server"

                Text='<%# Bind("profilename") %>' />

 

Do the same for age and email textbox fields.

 

4. You can put double spaces between the fields, so that they will look cleaner:

5. The default submission uses the “Insert” hyperlink. You may need to change this into a “Submit” button by going to the Source Code view and then changing the <asp:LinkButton to simply <asp:Button, for example:

<asp:Button ID="InsertButton" runat="server" CausesValidation="True"

                    CommandName="Insert" Text="Submit" /> 

You may add more space between the submit button and the rest of the web form. Configuring and formatting InsertItemTemplate in FormView is complete; your template should now look like this:

User Input Validation of Name, Age and Email Fields

It is always a good practice to validate everything before inserting it into the database. This will ensure that the collected data is of the correct data type and in the correct format. It also offers some advantages in terms of security, because validation can prevent illegal inputs.

I encourage you to refer to the tutorial series listed below on ASP.NET 3.5 Input validation if you are not familiar with this:

http://www.aspfree.com/c/a/ASP.NET/ASPNET-35-User-Input-Validation-Basics/

http://www.aspfree.com/c/a/ASP.NET/Validating-User-Input-with-ASPNET-35/

http://www.aspfree.com/c/a/ASP.NET/Completing-a-Basic-ASPNET-35-User-Input-Validation-Project/

Okay, so let's assume you have read it and understand validation controls. You will apply validation to the following fields: name, age and email. As a rule, it is suggested that RequiredFieldValidator be used for all three fields, along with CompareValidator to check the data type and RegularExpressionValidator for checking the syntax/format of the email submitted.

For the data type, the name will be a string while the age is an integer. You might not need to check the data type for email, because you will directly check the syntax using regular expression techniques.

You can also customize the error messages to make them more meaningful.

Finally, you can see the InsertItemTemplate tag source code with validation lines in blue font (bolded) below. 

<InsertItemTemplate>

            Enter your name:

            <asp:TextBox ID="profilenameTextBox" width="192px" runat="server"

                Text='<%# Bind("profilename") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator1"

                        runat="server" ErrorMessage="Please enter your name" ControlToValidate="profilenameTextBox"></asp:RequiredFieldValidator>
<asp:CompareValidator

                            ID="CompareValidator1" runat="server" ErrorMessage="Your name should be a string." Operator="DataTypeCheck" ControlToValidate="profilenameTextBox"></asp:CompareValidator>

            <br />

            <br />

            Enter your age:

            <asp:TextBox ID="profileageTextBox" width="49px" runat="server"

                Text='<%# Bind("profileage") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator2"

                        runat="server" ErrorMessage="Please enter your age" ControlToValidate="profileageTextBox"></asp:RequiredFieldValidator>
<asp:CompareValidator

                            ID="CompareValidator2" runat="server" ErrorMessage="Your age should be an integer." Operator="DataTypeCheck" ControlToValidate="profileageTextBox" Type="Integer"></asp:CompareValidator>

            <br />

            <br />

            Enter your email:

            <asp:TextBox ID="emailTextBox" width="192px" runat="server" Text='<%# Bind("email") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator3"

                        runat="server" ErrorMessage="Please enter your email" ControlToValidate="emailTextBox"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator

                            ID="RegularExpressionValidator1" runat="server" ValidationExpression="w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*" ControlToValidate="emailTextBox" ErrorMessage="Your email is in incorrect syntax."></asp:RegularExpressionValidator>

            <br />

            <br />

            <asp:Button ID="InsertButton" runat="server" CausesValidation="True"

                CommandName="Insert" Text="Submit" />

            &nbsp;

</InsertItemTemplate>

 

As you noticed, all validation control lines should be placed after the Textbox control. Also, the equivalent Design view of the project will be:

GridView Web Control to Retrieve Records

Drag the GridView Web Control from View à Toolbox à Data and place it below the FormView web control.

Right click on it and click “Show Smart Tag.” In Choose Data Source, select SqldataSource1.

Go again to Show Smart Tag and click “Edit Columns.” Under “Selected Fields,” select profileid and delete it (red x button) then click OK.

Also in the “Edit Columns” section, you need to change the column header text to something more meaningful. For example:

a. Changing profilename to Name

b. Change profileage to Age

c. Change email to Email

To edit these items, click the field under “Selected Fields” and then, under “BoundField propertiesà Appearance à HeaderText, change the HeaderText to the meaningful text. Finally, click OK.

Adjust the width of the Gridview to 303px by dragging it in Design view to extend its width, as shown in the screen shot below:

The Gridview configuration is complete. It should look like this (in Visual Web Developer Design View):

Final Project Output and Source Code

Finally, go to File à View in your browser and try inputting records. If you have entered the format wrong, the validation error message will pop up as designed. When there is no validation error, click Submit; Gridview will display the records you just inserted into the database.

Example:

 

The complete Default.aspx source code can be downloaded here:

http://www.dotnetdevelopment.net/tutorials/insertitemtemplate_formview.zip

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials