Blue Theme Orange Theme Green Theme Red Theme
 
Dundas Dashboard
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Dundas Dashboard
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Validation Controls within GridView control in ASP.NET 2.0

Validation Controls within GridView control in ASP.NET 2.0

This article is intended to show how to add customized validation features to GridView control in order to avoid mistakes when the users enter data and violates the underlying business rules.

Author Rank:
Technologies: .NET 2.0, ASP.NET 2.0,Visual C# .NET
Total downloads :
Total page views :  2000
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor





Introduction

This article is intended to show how to add customized validation features to GridView control in order to avoid mistakes when the users enter data and violates the underlying business rules. Specifically I'm going to illustrate how to replace BoundField or CheckBoxField default generated fields with Template field in GridView controls. For illustrative purposes, we're going to use the table Production.Product (representing business entity Product) in the database AdventureWorks shipped with SQL Server 2005.

Developing the solution

The main requirements are to display a list of products (fields to display are ProductID, Name, ProductNumber, ListPrice) and then extend the behavior of the underlying GridView control to provide validation controls to enforce that the name and list price fields are mandatory when inserted and updated.

The first step is to create a Web application by opening Visual Studio.NET 2005 and select File | New | Web Site for the front-end project. Let's create a Class Library project for the data access layer components. This separation of objects (concerning their responsibilities) follows the best practices of enterprise applications development.

Let's add a strongly typed DataSet item to the Class Library project (see Figure 1).

1.gif
 
Figure 1

Next step is to define a TableAdapter item representing the logic to access the Production.Product table in the database AdventureWorks by using a SQL statement (see Figure 2).

2.gif
 
Figure 2

Then let's add a SQL statement to update the product name and list price for a given product represented by its product identifier. This SQL statement is shown in Figure 3.

3.gif
 
Figure 3

The final schema for the data access objects resembles to Figure 4.

4.gif
 
Figure 4

Now let's go to the Web front-end project and add a reference to the data access project (the Class Library project created before) and then add Web form to the project named ValidationControlsForm.aspx.

Next step is to drag and drop an ObjectDataSource item from the Toolbox onto the Web form, set the ID property to odsProducts and click on the smart tag and select the Configure Data Source option in order to launch the configuration wizard.

In the first page (Choose a Business Object) you must select the ProductTableAdapter (see Figure 5).

5.gif
 
Figure 5

Click on the Next button. In the Select tab, choose the GetData method (see Figure 6).

6.gif
 
Figure 6

In the Update tab, you must choose the former created UpdateNameAndListPrice method (see Figure 7).

7.gif
 
Figure 7

Click on the Finish button.

Next step is to drag and drop a GridView control from the Toolbox onto the Web Form, set the ID property to gvProducts, and click on the smart tag to bind itseft to the odsProducts ObjectDataSource. You must also check the Enable Editing and Enable Paging option (see Figure 8).

8.gif
 
Figure 8

If you see the Select operation, this will return four columns ProductID, [Name], ProductNumber, ListPrice for the table Production.Product. The Update operation expects only three parameters (ProductID, [Name], ProductNumber, ListPrice), so the ProductNumber does not need to be mapped to the Update operation. One way to achieve this is by deleting this column as a field of the GridView control or by setting the Readonly property to True (see Figure 9).

9.gif
 
Figure 9

Now, one last trick must be used so as to update correctly. You must go to the OldValuesParameterFormatString attribute of the asp:ObjectDataSource ASP.NET tag, and change the value from original_{0} to {0}. You can also see that the fields in the GridView control are all of the type BoundField. The final code for the presentation page is shown in the Listing 1.


<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidationControlsForm.aspx.cs" Inherits="ValidationControlsForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:ObjectDataSource ID="odsProducts" runat="server" OldValuesParameterFormatString="{0}"

            SelectMethod="GetData" TypeName="ObjDataSourceDACPkg.DSProductionTableAdapters.ProductTableAdapter"

            UpdateMethod="UpdateNameAndListPrice">

            <UpdateParameters>

                <asp:Parameter Name="Name" Type="String" />

                <asp:Parameter Name="ListPrice" Type="Decimal" />

                <asp:Parameter Name="ProductID" Type="Int32" />

            </UpdateParameters>

        </asp:ObjectDataSource>

   

    </div>

        <asp:GridView ID="gvProducts" runat="server" AllowPaging="True" AutoGenerateColumns="False"

            DataKeyNames="ProductID" DataSourceID="odsProducts">

            <Columns>

                <asp:CommandField ShowEditButton="True" />

                <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"

                    ReadOnly="True" SortExpression="ProductID" />

                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

                <asp:BoundField DataField="ProductNumber" HeaderText="ProductNumber" SortExpression="ProductNumber" ReadOnly="True" />

                <asp:BoundField DataField="ListPrice" HeaderText="ListPrice" SortExpression="ListPrice" />

            </Columns>

        </asp:GridView>

    </form>

</body>
</html>

Listing 1

If you run the application, you could enter new values for the products, although if you enter a value that violated the constraints of your solutions (for example, leave empty the product name field), then you will receive an exception because it refers to a NULL in the database.

One way to solve this problem is add validation control to the GridView control by converting BoundFields into TemplateFields. To achieve this, you need to click on the smart tag on the GridView control and select the Edit Columns option in order to launch the Fields window. Then select the Name field and click on the "Convert this field into TemplateField" link. Do the same operation with the ListPrice field.

When you convert a BoundField into a TemplateField, you generate the following data binding code (see Listing 2).


<
asp:GridView ID="gvProducts" runat="server" AllowPaging="True" AutoGenerateColumns="False"

            DataKeyNames="ProductID" DataSourceID="odsProducts">

            <Columns>

                <asp:CommandField ShowEditButton="True" />

                <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"

                    ReadOnly="True" SortExpression="ProductID" />

                <asp:TemplateField HeaderText="Name" SortExpression="Name">

                    <EditItemTemplate>

                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>

                    </EditItemTemplate>

                    <ItemTemplate>

                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:BoundField DataField="ProductNumber" HeaderText="ProductNumber" SortExpression="ProductNumber" ReadOnly="True" />

                <asp:TemplateField HeaderText="ListPrice" SortExpression="ListPrice">

                    <EditItemTemplate>

                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("ListPrice") %>'></asp:TextBox>

                    </EditItemTemplate>

                    <ItemTemplate>

                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("ListPrice") %>'></asp:Label>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>
        </asp:GridView>

Listing 2

The EditItemTemplate and the InsertItemTemplate display the data field value in the Text property of TextBox controls using the two-way data binding techniques (the <%# Bind("FieldName") %> syntax).

Next step is to make sure that field values for the product name and list price are mandatory, and to achieve this, you're going to use the RequiredFieldValidator validator control. Go to the EditItemTemplate node for Name and ListPrice fields and add the RequiredFieldValidator tag (see Listing 3).

<EditItemTemplate>
  <
asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name")  %>'></asp:TextBox>
  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"  ControlToValidate="TextBox1" ErrorMessage= "* Required  Field"></asp:RequiredFieldValidator>
</EditItemTemplate>

Listing 3

Now if you run the application and attempt to omit the product name or list price, you will see an asterisk and a message next to the textbox indicating that this is a required field.

Conclusion

In this article, I've discussed the main techniques to add customized validation logic to enforce business rules on the presentation layer of your solution. In this case, we have to convert the BoundFields into TemplateFields in order to add validation controls. Now you can apply this techniques in your own situation.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
John Charles Olamendy
He’s a senior Integration Solutions Architect and Consultant. His primary area of involvement is in Object-Oriented Analysis and Design, Database design , Enterprise Application Integration, Unified Modeling Language, Design Patterns and Software Development Process. He has knowledge and extensive experience in the development of Enterprise Applications using Microsoft.NET and J2EE technologies and standards. He is proficient with distributed systems programming; and business-process integration and messaging using the principles of the Services Oriented Architecture (SOA) and related technologies such as Microsoft BizTalk Server, Web Services (Windows Communication Foundation, WSE, BEA WebLogic, Oracle AS and Axis) through multiple implementations of loosely-coupled system. He’s a prolific blogger contributing to .NET and J2EE communities and actively writes articles on subjects relating to integration of applications, business intelligence, and enterprise applications development. He holds a Master’s degree in Business Informatics at Otto Von Guericke University, Magdeburg, Germany. He was recently awarded as MVP. He currently works in the telecommunication industry and delivers integration solutions for this industry. He harbors a true passion for the technology.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved