YOUR FEEDBACK
johnpetersen wrote: Great post. You hit some good points, and hopefully me sending this post. It wil...

SYS-CON.TV
TOP MICROSOFT .NET LINKS


.NET Cover Story — Adding Validation Capabilities to a BoundField
Using ASP.NET

The new family of bound controls lets developers build data-driven applications almost without writing a line of code at page level, but there's more work to do to build really robust, fully featured controls.

With the new version of .NET Framework, developers can extend base controls to build "powered" ones that satisfy particular needs that base controls can't.

In this article you'll see how to extend the BoundField control adding validation capabilities using ASP.NET validation controls. These controls provide two ways of validation: server-side and client-side. The nice thing about these validation controls is that they will do client-side validation when they detect that the browser can (unless client-side validation has been disabled), thus reducing roundtrips. And it will do server-side where necessary. This client-side/server-side detection and validation are done without extra work by the developer.

BoundField Control
The BoundField control is used by data-bound controls (such as GridView and DetailsView) to display the value of a field as text.

In edit/insert mode the control displays a textbox where the user can change the value of the underlying field. With a base BoundField you can't validate the user input in any way so you have to check the server side to see that, for example, all the mandatory fields are filled and all the rules for special fields (like e-mail fields) are satisfied.

In the case of an error you have to submit data to the user so he or she can correct the mistake and do this until all the fields are filled correctly.

You could avoid all the roundtrips to the server if you could check for data correctness on the client side (of course, to check the correctness server-side is a best practice that I warmly advise).

Using validator controls is a way to do client-side validation; a detailed description of the validator controls are outside the scope of this article so if you want a detailed description, point your browser to http://msdn.microsoft.com/library/default.asp?url=/library/ en-us/cpgenref/html/cpconaspnetsyntaxforvalidationcontrols.asp.

The goal now is to extend a BoundControl so that, in edit or insert mode, user input can be validated against a validation control.

The PoweredBoundFiled Class
First of all create a class that inherits from the BoundField class (see Listing 1). This lets you start with a class that behaves exactly like a generic BoundField control.

You have to add properties and override methods to implement the validation feature. The PoweredBoundField control will support the required validation and regular expression validation capabilities, so the first step is to create some properties to carry some information about this.

Add the following public properties:

  • Required: The Boolean value that indicates if the field is mandatory.
  • RequiredErrorMessage: The string value that represents the error message displayed to the user when he or she leave a required field blank.
  • RegularExpressionValidationString: The string value that represents the regular expression to be satisfied by the data inserted in the bound field.
  • RegularExpressionValidationErrorMessage: The string value that represents the error message displayed to the user when he or she inserts an invalid expression.
Listing 2 shows some of these properties (note that the property value is stored in the ViewState to preserve it from postbacks).

The properties just created let you define the behavior of the control and what kind of validation controls have to be injected when the control is rendered.

Add a RequiredFieldValidator control if the required property is set to true; add a RegularExpressionValidator control if the RegularExpressionValidationString property isn't empty.

The RegularExpressionValidationErrorMessage property and the RequiredErrorMessage property let the developer customize the error message to present to the user in case of erroneous inputs (note that these properties have a default value for displaying a generic message).

PoweredBoundField Overrides
The validation feature of the PoweredBoundField control is provided by validation controls; you have to bind these controls to the TextBox displayed in edit or insert mode.

You already know that you have to execute this task in the InitializeCell method (see Listing 3).

First, call the base method since you have to add some stuff and not override the standard behaviour.

base.InitializeCell(cell, cellType, rowState, rowIndex);

MyBase.InitializeCell(cell, cellType, rowState, rowIndex)

Then if the current row is a data row (neither a header nor a footer) and if the current row is in edit or insert mode, find the TextBox bound to the DataField.

TextBox tb = (TextBox)cell.Controls[0];

Dim tb As TextBox = CType(cell.Controls(0), TextBox)

Then set the TextBox id that you will use to link the possible validation controls.

tb.ID = DataField;

tb.ID = DataField

Finally add a RequiredFieldValidator control to the current cell if the Required property is true and/or add a RegularExpressionValidator control if the RegularExpressionValidationString property isn't blank.

These controls are associated with the TextBox bound to the DataField via the ControlToValidate property.

Two functions are created to encapsulate the validation control creation process. There create a new instance of the validation control then set some control values (Listing 4 shows one of these functions).

PoweredBoundField at Work
Now you can see the new Powered-BoundField in action; first compile the above class in a class library dll then use it inside an aspx page. (You can download the whole Visual Studio 2005 solution from the online version of this article at http://dotnet.sys-con.com.)

You'll use the PoweredBoundField control just created inside a GridView control that will bind to a table in the AdventureWorks sample database that ships with SQL Server 2005 (to run this example you can download Microsoft SQL Server 2005 Express Edition at http://www.microsoft.com/downloads/ details.aspx?familyid=220549b5-0b07-4448-8848-dcc397514b41&displaylang=en and the AdventureWorks sample database at http://www.microsoft.com/downloads/details.aspx? familyid=9697AAAA-AD4B-416E-87A4-A8B154F92787&displaylang=en ).

Remember to add a SQL Server login so that the connection string you find in the web.config file works correctly, otherwise change the connection string with a suitable login account.

Let's look at the aspx code (see Listing 5).

First register the control at page level with a Register directive:

<%@ Register Assembly="Powered01Cs" Namespace="Powered01Cs" TagPrefix="Powered01Cs" %>

<%@ Register Assembly="Powered01Vb" Namespace="Powered01Vb" TagPrefix="Powered01Vb" %>

This creates an association between a tag prefix and the control that provides a concise way to refer to it in the aspx page. Then note that you have to put a ValidationSummary control on top of the form because even if you've built the control with all the features to present nice error messages to the user, you still have to collect all the error messages at page level.

<asp:ValidationSummary ID="ValidationSummary1" Runat="server" />

In the GridView declaration the cool portion is the Columns fragment; note that you can mix native BoundField controls with PoweredBoundField controls. From the Purchasing.Vendor table of the AdventureWorks sample database you'll manage three fields (this is enough for the sample):

  • A read-only VendorID (ID)
  • A required Account Number that has to be composed of at least one upper case letter followed by four digits
  • A required Name
To test the control run the Default.aspx (or DefaultVb.aspx) page, then click one edit link of the GridView to edit the fields values then change the contents of the fields so that some of the former rules are violated, and finally click the update link to see how it happens.

As you can see from Figure 1, the error messages are displayed depending on what field contains the erroneous values; and, of course, the page doesn't post back until you don't insert right values.

Please note that to develop this fully featured page you didn't have to write a single line of code at page level.

Conclusion
The new family of bound controls lets developers build data-driven applications almost without writing a line of code at page level, but there's some other work to do to build really robust fully featured controls.

With the new version of the .NET Framework developers can extend base controls to build "powered" ones that satisfy particular needs that base controls can't.

In this article you saw how to extend a base-bound control adding validation capabilities using ASP.NET validation controls.

In this way you could validate user input during the edit of a GridView row.

As a result you've built a data access page with validation capabilities without writing a line of code at page level.

About Oscar Peli
Oscar Peli is a .NET Solution Architect and Pda/Smartphone chief in Ancona (Italy) Town Council.Assistant at Macarata University where I develop web based applications to support research projects.

YOUR FEEDBACK
Christoffer Munck wrote: Oh man, forgot to add this to the command field in the grid: <asp:CommandField ... ValidationGroup="UpdateMeasure"></asp:CommandField> Now everything works :)
Christoffer Munck wrote: Hi' i've just seen you control and implemented. Works great. I do however have a problem when implementing ValidationGroup like this: rfv.ValidationGroup = inValidationGroup; Then the validation stops working. It does display the (!) alright. But it allows for postbacks now :( Do you know of any issues concerning validationgroup that you should be aware of? Best regards Christoffer Munck
MIchael wrote: Great idea Oscar, but the article listing links are broken and I can't find the solution download. Thanks!
Oscar Peli wrote: cj, I will check with the editors then I will let you a line to tell you how to get the whole project. Thanks for your comment.
cj wrote: i noticed a sentence saying that we could download the example from the web site. i've looked everywhere i can think of, but i haven't seen a download link.
SYS-CON Australia News Desk wrote: The new family of bound controls lets developers build data-driven applications almost without writing a line of code at page level, but there's more work to do to build really robust, fully featured controls. With the new version of .NET Framework, developers can extend base controls to build 'powered' ones that satisfy particular needs that base controls can't.
MICROSOFT .NET LATEST STORIES
In a move that looks tailor-made for an antitrust suit, Microsoft says it’s going to give away a consumer security kit that it’s building code named Morro. It should be available in the second half of next year – probably more like mid-year. The freebie widgetry is supposed to de...
OpenSpan and TIBCO have announced a technology and business partnership designed to extend TIBCO solutions to desktop environments. The partnership will enable TIBCO Service-Oriented Architecture, Business Process Management and Business Optimization solutions to more rapidly integrate...
Tidal Software has announced Intersperse 8.0, a product that monitors J2EE and .NET applications and their transaction component performance to produce meaningful metrics for managing applications and high-level business processes. The product leverages a combination of lightweight Ja...
DataGuise has announced their first masking in place solution for multi-database environments such as Oracle, Microsoft SQL Server, and others. The dgSolution Suite provides secure masking of database content and is designed for the highest level of flexibility and functionality across...
The BlackBerryR Technical Webcast Series is designed to help BlackBerry administrators better manage and leverage the capabilities of their BlackBerry solution. Each webcast is packed with detailed technical information, covering topics that are relevant to you. Our on-demand webcasts ...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING NEWS FROM THE WIRES
Collexis Holdings, Inc. (OTC Bulletin Board: CLXS), a leading developer of semantic search and knowl...