Operating data 19 in ASP.net 2.0: Adding validation controls to the edit and add-in interface-self-study process

Source: Internet
Author: User
Tags extend

Introduction

In the examples in the previous sections, the GridView and DetailsView controls use bound columns and CheckBoxField (when binding the GridView and DetailsView, a smart tag allows vs to automatically increase the corresponding type based on the database). When you edit a row in the GridView or DetailsView, the bound column of the non-read-only property is automatically converted to a textbox so that the user can modify the existing data. Similarly, when new records are added to the DetailsView control, the bound columns with the InsertVisible property to True (the default) render an empty textbox to accept user input. The same is true for CheckBoxField columns, which are usually displayed as read-only checkbox and accept selections when new/edited records are added.

Although the editing and adding interfaces provided by BoundField and CheckBoxField are quite useful, they lack verification capabilities. When the user produces some data entry errors-such as omitting the ProductName field or entering an invalid value for UnitsInStock (i.e.-50)-then the application throws an exception from the bottom. Although we can handle this anomaly well as discussed in the previous tutorial previous tutorial, a perfect ' Add/edit ' user interface should include validation controls that prevent users from entering these invalid data at the first time.

In order to provide a custom new/edit interface, you need to replace BoundField and CheckBoxField with template columns (Itemplatefield). With regard to the template column, it has been discussed in the tutorial "using Templatefields in" The GridView control and the using Templatefields in the DetailsView control, with several different row-like form of the template. The item template (ItemTemplate) of the template column, which renders the read-only field or row in the DetailsView or GridView control, while Edititemplate and InsertItemTemplate are the interface templates for Edit and new mode respectively.

In this tutorial, you will find how simple it is to provide validation controls for the EditItemTemplate and insertitemtemplate of template columns to provide a more robust user interface. To be clear, this tutorial uses the sample code created in the examining the Events associated with inserting, updating, and deleting to add validation to the new/edit.

Copy of the sample code for the research on INSERT, UPDATE and delete associated events

In the "Research insert, update, and delete associated events" tutorial, we created a page that displays the name and price of the product in an editable GridView list. The page also has a Detailsview,defaultmode property set to insert, so it is always rendered as a new mode. By DetailsView, users can enter names and prices to add new products, click Insert, the new product is added to the system (see Figure 1).

Figure 1: Previous code allows users to add new products or modify existing ones

The goal of this section tutorial is to provide validation controls for the DetailsView and GridView. More precisely, this validation logic will be:

· Name is required when new/edit product
· Price is required for new records, and prices are still required for editing, and the program logic in the previous tutorial previous tutorial is applied in the RowUpdating event handling of the GridView
· Make sure that the price you entered is in a valid currency format

Before considering adding validation to the previous code, we first need to copy the code from the previous tutorial previous tutorial sample datamodificationevents.aspx to the uivalidation.aspx page of the tutorial in this section. To complete this point you need to copy the element tag of the DataModificationEvents.aspx page and its background code. First copy the element tags by following these steps:

1. Open datamodificationevents.aspx in Visual Studio
2. Go to the Source view of the page (click the Source button at the bottom of the page)
3. Text between the copy <asp:Content> to </asp:Content> tags (3 to 44 lines), as shown in Figure 2.

Figure 2: Text in copy <asp:Content> control

4. Open uivalidation.aspx Page
5. Go to the Source view of a page
6. pasting text to <asp:Content> controls

Then open the code file DataModificationEvents.aspx.cs, copy the code in the Editinsertdelete_datamodificationevents class, and 3 event handling (Page_Load, Gridview1_rowupdating, and objectdatasource1_inserting), be careful not to copy class declarations and using statements, and then paste them into the UIValidation.aspx.cs In the editinsertdelete_uivalidation.

After the work above, do not rush to start a cup of tea in the browser to see if the error, the two pages should have the same output and function. (Refer to Figure 1, datamodificationevents.aspx at run time).

Convert a bound column to a template column

To add validation controls to the new/edit interface, the DetailsView and GridView must convert the bound columns to template columns. To implement this transformation, first click on the GridView smart tag (the arrow in the top right-hand corner of the GridView), select ' Edit Column ... ' (Edit Columns), select the bound field in the left, and click ' Convert this field to TemplateField ' link (English is convert this field to a TemplateField, below).

Figure 3: Converting the bound columns of DetailsView and GridView to template columns

The fields that you just manipulated (English is Fields) dialog box, the binding column can be converted to a template column, the same has read-only, edit, add the original features. The following code shows the element markup for the ProductName field that is converted to a template column in DetailsView:

<asp:templatefield headertext= "ProductName" sortexpression= "ProductName" >
  <EditItemTemplate>
    <asp:textbox id= "TextBox1" runat= "server" text= ' <%# Bind ("ProductName") > ' ></asp:TextBox>
  </EditItemTemplate>
  <InsertItemTemplate>
    <asp:textbox id= "TextBox1" runat= "Server" Text= ' <%# Bind ("ProductName")%> ' ></asp:TextBox>
  </InsertItemTemplate>
  < itemtemplate>
    <asp:label id= "Label1" runat= "server" text= ' <%# Bind ("ProductName")%> ' ></asp: label>
  </ItemTemplate>
</asp:TemplateField>

Note that the template column automatically creates three template columns, ItemTemplate, EditItemTemplate, and InsertItemTemplate. Item template ItemTemplate Use the Label Web control to display field values (ProductName) in a simple, EditItemTemplate and InsertItemTemplate Use the TextBox control and use its Text property to process the related data. Since we only use DetailsView on the page to implement new additions, you can delete ItemTemplate and EditItemTemplate, of course, it doesn't matter if you keep them.

Because the GridView does not support DetailsView additions, convert the ProductName field of the GridView to a template column and retain only ItemTemplate and EditItemTemplate:

<asp:templatefield headertext= "ProductName" sortexpression= "ProductName" >
  <EditItemTemplate>
    <asp:textbox id= "TextBox1" runat= "server" text= ' <%# Bind ("ProductName")%> ' ></asp:TextBox>
  </EditItemTemplate>
  <ItemTemplate>
    <asp:label id= "Label1" runat= "server" text= ' <%# Bind ("ProductName")%> ' ></asp:Label>
  </ItemTemplate>
</asp:TemplateField>

By clicking the ' Convert this field to TemplateField ' link, Visual Studio creates a template column that simulates a bound column interface, which can be verified by viewing the page in the browser, and the appearance and behavior should be identical before and after the substitution.

  Note: You can customize the editing interface in the template as needed. For example, maybe we use a smaller textbox for the UnitPrice field. To do this, you can specify a fixed width by setting the Columns property of the TextBox or by using the Width property. The next section of the tutorial discusses how to customize the editing interface with other data entry Web controls that replace the TextBox.

Iii. adding validation controls for the GridView Item edit template (EditItemTemplate)

When creating data entry forms, it is important to restrict user input to required, legal, and formatted data. To ensure that the user input data is valid, ASP. NET provides 5 built-in validation controls to verify the value of a single control:

· requiredfieldvalidator– calculate the value of the input control to ensure that the user enters a value
· comparevalidator– compares the value of an input control with the value of a constant value or other input control to determine whether the two values match the relationship specified by the comparison operator (less than, equal to, greater than, type, and so on)
· rangevalidator– calculates the value of the input control to determine whether the value is between the specified upper and lower bounds
· regularexpressionvalidator– calculates the value of the input control to determine whether the value matches the pattern defined by a regular expression
· customvalidator– calculates the value of the input control to determine whether it passes the custom validation logic

For more information on these five controls, see Validation Controls section in asp.net Quickstart tutorials.

In this tutorial, we need to use RequiredFieldValidator for the ProductName template columns in DetailsView and GridView. The DetailsView UnitPrice template column also requires a RequiredFieldValidator. Additionally, you need to add a comparevalidator to all UnitPrice template columns to ensure that the price entered is greater than or equal to 0 and is in a valid currency format.

Note: These validation controls are already included in the ASP.net 1.x, but some improvements are added to ASP.net 2.0, and the main two points are client-side scripting support for non-IE browsers and a group of specific validation controls that group some of the validation controls on the page to implement a button, see Dissecting the Validation Controls in asp.net 2.0 (translator: Also refer to MSDN http://msdn.microsoft.com/asp.net/ Default.aspx?pull=/library/en-us/dnvs05/html/valgroups.asp).

Now we're going to add these validation controls to the EditItemTemplate in the GridView template column. First click on the GridView smart Tag Select Edit Template to open the template editing interface, and then select the template you want to edit from the Drop-down list. Since we're dealing with the editing interface, here we'll add validation controls to the EditItemTemplate templates for ProductName and UnitPrice.

Figure 4: Expanding the EditItemTemplate template for ProductName and UnitPrice

In the EditItemTemplate of ProductName, add a RequiredFieldValidator to the editing interface from the toolbox by dragging it behind the textbox.

Figure 5: Add a RequiredFieldValidator for the EditItemTemplate of the ProductName

All validation controls can only serve a single ASP.net Web control, so the new validation control needs to be validated for the EditItemTemplate TextBox control, which requires the ID of the validation control to be set to the validation control's ControlToValidate Property Properties. The current ID of the textbox may be a momin TextBox1, we'd better give it a more appropriate ID, click the textbox in the template, press F4 to view the Properties window, and change the ID from TextBox1 to editproductname.

Figure 6: Renaming the textbox ID to Editproductname

Next, set the RequiredFieldValidator ControlToValidate property to Editproductname. Finally, set the ErrorMessage property to "You must provide the product ' name" and set the Text property to "*". If you set the Text property, the text value is displayed when the validation fails. The ErrorMessage property is also required, it is prepared for ValidationSummary, and when the Text property value is omitted, the ErrorMessage property is also displayed as text when invalid input.

After you set these properties for RequiredFieldValidator, the screen should look like Figure 7:

Figure 7: Setting the ControlToValidate, ErrorMessage, and Text properties of the RequiredFieldValidator control

With the addition of RequiredFieldValidator for ProductName EditItemTemplate, the rest is to add some necessary validation controls for the UnitPrice edititemplate template. We do not need requiredfieldvalidator because we have decided to unitprice the editor as an optional fill. However, you need to add a comparevalidator to ensure that the UnitPrice is valid, must be greater than or equal to 0, and currency format.

Before adding CompareValidator to the EditItemTemplate template for UnitPrice, change the ID of the textbox to Editunitprice. Then add the CompareValidator control and set the ControlToValidate property to the Editunitprice,errormessage property is "The price must is greater than or equal to Zero and cannot include the currency symbol, and the Text property is "*".

To ensure that the UnitPrice value must be greater than or equal to 0, the CompareValidator operator property is set to the Greaterthanequal,valuetocompare property of "0" and the Type property is currency. The following code shows the EditItemTemplate adjusted appearance in the UnitPrice template column:

<EditItemTemplate>
  <asp:textbox id= "Editunitprice" runat= "server" text= ' <%# ' Bind ("UnitPrice", "{0:c ")%> ' columns=" 6 "></asp:TextBox>
  <asp:comparevalidator id=" CompareValidator1 "runat=" Server " Controltovalidate= "Editunitprice" errormessage= "The price must is greater than or equal to zero and cannot include the Curr Ency symbol "operator=" greaterthanequal "type=" Currency "valuetocompare=" 0 ">*</asp:CompareValidator>
</EditItemTemplate>

After these adjustments, view the page in the browser. If you try to omit name or enter an invalid price for product editing, the asterisk appears behind the text box. As shown in Figure 8, price containing the currency compliance, such as $19.95, will be considered invalid. The currency type of the CompareValidator control allows a numeric separator (like a comma, a decimal point, depending on the culture setting) to begin with a sign, but not a currency symbol. The editing interface, UnitPrice, is presented as a currency, and this behavior can be confusing to the user.

  Note: Think back to the tutorial on "Research inserts, updates, and deletes", and we set the DataFormatString property of the bound column to {0:C} to format it as currency. Because we set the Applyformatineditmode property to True, the GridView editing interface formats UnitPrice into currency format. When bound columns are converted to template columns, these settings are preserved and the Text property of the textbox is formatted using the binding syntax <%# bind ("UnitPrice", "{0:c}")%>.

Figure 8: The asterisk displayed after the text box when invalid input

Based on such validation, it is difficult to accept that the user must manually delete the currency symbol when editing the record. Here are three options for remediation:

1. Configure EditItemTemplate so that UnitPrice will not be formatted as currency.
2. Remove the CompareValidator and replace it with RegularExpressionValidator, allowing the user to enter a currency symbol, but write code to accommodate different cultural settings.
3. Remove the validation control and perform server-side validation logic in the RowUpdating event handling of the GridView.

We use the first approach here. UnitPrice is converted to currency format through the binding expression <%# bind ("UnitPrice", "{0:C}") in EditItemTemplate. Change it to bind ("UnitPrice", "{0:n2}") to a number formatted as two decimal digits. These actions can be done directly in the element tag, or by clicking the ' edit DataBindings ... ' link in the Editunitprice text box (see Figure 9, Figure 10)

Figure 9: Click on the ' Edit DataBindings ' link in textbox

Figure 10: Specifying a specific format for a binding expression

After these changes, the price of the editing interface is formatted as a comma and decimal point, but without a currency symbol.

  Note: The UnitPrice EditItemTemplate does not contain RequiredFieldValidator, runs the postback, and continues to update the logic. However, the RowUpdating event handling that was copied in the "Research insert, update, and delete associated events" tutorial contains the check code for the provided UnitPrice. Delete logic, keep it as it is, or give UnitPrice EditItemTemplate increase RequiredFieldValidator.

IV: Data entry issues on the overview page

In addition to these 5 validation controls, ASP. NET contains a summary control ValidationSummary controls that display the errormessage of validation controls that detect invalid data. Summarize the error results at a location on the page as text, or through a client message box. Here we add a client message Box Overview page for the program to all the validation issues.

Dragging a ValidationSummary control from the Toolbox to the design window does not require a location because we intend to display it as a message box. After adding the control, set its ShowSummary property to false and set the ShowMessageBox property to True. Since then, all validation errors will be displayed in a Client message box.

Figure 11: Validation error Summary in the client message box (click to enlarge)

V. Adding validation controls for DetailsView InsertItemTemplate

The remainder of this tutorial adds validation controls to the new interface for DetailsView. This work is no longer the same as the third bar. As mentioned in the edititemtemplates operation of the GridView, the ID of the rename textbox is recommended, using Insertproductname and Insertunitprice instead of TextBox1 and TextBox2, respectively.

Add the RequiredFieldValidator validation control for the ProductName InsertItemTemplate and set its controltovalidate to the ID of the textbox in the template, and set the Text property to "*". The ErrorMessage property is "You must provide the product ' name".

Because the UnitPrice on the page is required for the new record, we add RequiredFieldValidator for it in the insertitemtemplate of UnitPrice, set ControlToValidate, Text and errormessage related properties. Finally, add the appropriate CompareValidator to the UnitPrice InsertItemTemplate, and configure its CompareValidator with reference to the previous UnitPrice increase ControlToValidate Text, ErrorMessage, Type, operator, and ValueToCompare related properties.

By adding these validation controls, the new product will be rejected by the system if it does not provide name or the price is negative or the illegal format is added.

Figure 12:detailsview Validation logic added in new interface (click to enlarge)

Vi. Grouping validation controls

There are two sets of logically separate validation controls on the page: the editing interface of the GridView and the corresponding two groups in the DetailsView new interface. By default, all validation on the page will take effect when postback occurs. Obviously, when we edit the record we don't want the validation of DetailsView's new functionality to work, Figure 13 illustrates the awkward situation-when the user enters some valid data while editing product, the validation error occurs when the update is clicked because of the name and price whitespace in the new feature.

Figure 13: Validation controls that update product to raise new functionality (click to enlarge)

The validation controls in ASP.net 2.0 can be grouped by using the ValidationGroup property. To associate these validation controls to a group, you simply specify the ValidationGroup property to the same value. In this tutorial, the ValidationGroup property in the GridView template is set to Editvalidationcontrols, and the DetailsView in the template The ValidationGroup property is Insertvalidationcontrols. The above actions can be done directly in the Code editing window or through the Properties window of the designer template editing interface.

ASP.net 2.0, in addition to validation controls, button and button-related controls also add ValidationGroup properties. Validation controls in a validation group are detected only when a button with the same ValidationGroup property produces postback, for example, to enable a new button in DetailsView to trigger a insertvalidationcontrols validation group. We specify the ValidationGroup attribute of CommandField as insertvalidationcontrols (Figure 14), while the ValidationGroup property of the CommandField in the GridView is specified as Editvalidationcontrols.

Figure 14: The ValidationGroup property of the CommandField in the set DetailsView is Insertvalidationcontrols

After these actions, the templates for DetailsView and GridView Templatefields and Commandfields are roughly as follows: TemplateField templates and CommandField templates in DetailsView:

<asp:templatefield headertext= "ProductName" sortexpression= "ProductName" > <InsertItemTemplate> <asp : TextBox id= "Insertproductname" runat= "server" text= ' <%# Bind ("ProductName")%> ' ></asp:TextBox> &L
      T;asp:requiredfieldvalidator id= "RequiredFieldValidator2" runat= "Server" controltovalidate= "Insertproductname" Errormessage= "You must provide the product name" validationgroup= "Insertvalidationcontrols" >* edfieldvalidator> </InsertItemTemplate> </asp:TemplateField> <asp:templatefield headertext= " UnitPrice "sortexpression=" UnitPrice "> <InsertItemTemplate> <asp:textbox id=" insertunitprice "runat=" se RVer "text= ' <%# Bind (" UnitPrice ")%> ' columns= ' 6 ' > </asp:TextBox> <asp:requiredfieldvali Dator id= "RequiredFieldValidator3" runat= "Server" controltovalidate= "Insertunitprice" errormessage= "you must p Rovide the product price "Validationgroup= "Insertvalidationcontrols" >* </asp:RequiredFieldValidator> <asp:comparevalidator id= "Co MpareValidator2 "runat=" Server "controltovalidate=" Insertunitprice "errormessage=" The price must is greater th  An or equal to zero and cannot include the currency symbol "operator=" greaterthanequal "type=" Valuetocompare= "0" validationgroup= "insertvalidationcontrols" >* </asp:CompareValidator> </insert itemtemplate> </asp:TemplateField> <asp:commandfield showinsertbutton= "True" validationgroup= " Insertvalidationcontrols "CommandField templates and Templatefields templates in the/> GridView: <asp:commandfield showeditbutton=" True "validationgroup=" Editvalidationcontrols "/> <asp:templatefield headertext=" ProductName "SortExpression=" "ProductName" > <EditItemTemplate> <asp:textbox id= "editproductname" runat= "server" text= ' <%# Bin
D ("ProductName")%> ' > </asp:TextBox>    <asp:requiredfieldvalidator id= "RequiredFieldValidator1" runat= "Server" controltovalidate= "Editproductname" Errormessage= "You must provide the product name" validationgroup= "Editvalidationcontrols" >*
     uiredfieldvalidator> </EditItemTemplate> <ItemTemplate> <asp:label id= "Label1" runat= "Server" Text= ' <%# Bind ("ProductName")%> ' ></asp:Label> </ItemTemplate> </asp:TemplateField> < Asp:templatefield headertext= "UnitPrice" sortexpression= "UnitPrice" > <EditItemTemplate> <asp:textbox ID
    = "Editunitprice" runat= "server" text= ' <%# Bind ("UnitPrice", "{0:n2}")%> ' columns= ' 6 ' ></asp:TextBox> <asp:comparevalidator id= "CompareValidator1" runat= "Server" controltovalidate= "Editunitprice" Errormessa Ge= "The price must is greater than or equal to zero and cannot include the currency symbol" operator= " Greaterthanequal "Type=" CurRency "valuetocompare=" 0 "validationgroup=" editvalidationcontrols ">* </asp:CompareValidator> &L t;/edititemtemplate> <ItemTemplate> <asp:label id= "Label2" runat= "server" text= ' <%# Bind ("UNITP Rice "," {0:c} ")%> ' > </asp:Label> </ItemTemplate> </asp:TemplateField>

When the GridView Update button clicks, the specific validation controls in the edit will start to detect, and when the new button in DetailsView is clicked, the validation of the new feature is in effect, and the highlighted part of Figure 13 shows the problem solved. However, after these changes, the ValidationSummary validation summary is no longer displayed when you enter invalid data. This is because the ValidationSummary control also owns the ValidationGroup property and displays only information from the validation control in the same validation group. Therefore, we need to use two validation controls, respectively, as Insertvalidationcontrols and editvalidationcontrols validation groups:

<asp:validationsummary id= "ValidationSummary1" runat= "Server"
  showmessagebox= "True" showsummary= "False"
  validationgroup= "Editvalidationcontrols"/>
<asp:validationsummary id= "ValidationSummary2" Server '
  showmessagebox= ' True ' showsummary= ' False '
  validationgroup= ' insertvalidationcontrols '/>

Here, this section of the tutorial will draw a full stop.

Summary

Although bound column BoundField can provide a new/edited interface, it cannot be customized. In many cases, we need to add validation capabilities to add/edit to ensure that users enter valid data. To do this, we convert BoundFields to TemplateField and add validation controls to the corresponding template. The tutorials in this section extend the code in the examining the Events associated with inserting, updating, and deleting. Added validation to the new and GridView editing interface for DetailsView. It also demonstrates how to use the ValidationSummary control to display validation summaries and how to group validation controls.

As you can see in this article, template columns allow you to add validation controls to the new/edit interface, and, of course, extend other Web controls. In the next tutorial, you will show how to replace the original textbox with a DropDownList control that can be data-bound, just through a foreign key (such as a CategoryID or SupplierID in the Products table).

I wish you a happy programming!

Author Introduction

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, "proficient in asp.net 2.0 within 24 hours" (English). His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog http://scottonwriting.net/.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.