Validating Data

Chapter 7 - Updating and Deleting Records
byJohn Kauffman, Fabio Claudio Ferracchiatiet al.?
Wrox Press ?2002

Whenever an application allows users to enter data, it must ensure that only valid input is passed to the system beneath - and that as a result, the data in the system is always meaningful. In general, there are two criteria that describe the validity and meaning of system data:

  • The data is valid in context. For instance, if your auction site stores users' e-mail addresses, you must ensure that the e-mail addresses that are entered into your site exist, and belong to the users who claim to own them. (A common practice here is to send a confirmation mail to the user, asking them to respond.) If your mail order application records a user's delivery address, you must ensure that the zip code matches the state and city entered.

  • Data integrity must be maintained. Data integrity refers to the consistency of data across different areas of a system. For instance, if your online ordering application categorizes products, you must ensure that each product belongs to a valid category. Furthermore, for as long as at least one product in the database belongs to a particular category, that category must not be deleted from the database.

In the last chapter, you saw that ASP.NET offers validation controls to help with the process of data validation. For example, you could link a RequiredFieldValidator control to a TextBox control to ensure that when creating a new category, the user enters something for the category name.

In this chapter - so far - we haven't applied any validation to our exercises, but that doesn't mean it's unnecessary. When we were updating data, we used the inline editing feature of the DataGrid control to allow users to change the price of any product. It would be sensible only to let users enter a positive price, and only to allow numeric entries. Similarly, when the user asked to delete a product, we could have determined programmatically whether there were any orders for it. If we found that there were, we could have prevented the attempt at deletion.

However, compared to other ASP.NET web server controls (such as the aforementioned TextBox) the DataGrid is validation-unfriendly. While ASP.NET can render textboxes for inline editing, it doesn't provide an interface to link a validation control with such a text box. This limitation makes client-side validation more difficult to implement for DataGrid than for some of the other controls. There are several possible solutions for this problem.

  • Perform data validation on the server - in other words, you validate the input when the page is posted back to the server. If the input is invalid, you don't update the database, and return an error message to the browser. The next exercise will implement this technique in the ASP.NET page used in the previous exercise.

  • Create templates for inline editing. As we saw briefly in Chapter 4, the DataGrid control allows you to define template columns, which are a combination of ASP.NET controls and HTML code blocks that allows you to fine-tune the layout and behavior of an edit field. You could, for example, create an 'edit box' template and link it to a validation control to provide client-side validation.

    For more details on this topic, take a look at Professional ASP.NET Special Edition, also from Wrox Press (ISBN 1-86100-703-5).

  • Use offline editing, in which you create a second page for editing a record that would use controls such as text boxes that can be linked to validation controls. When the user clicks an Edit link, you redirect them to this edit page. This technique also provides client-side validation.

  • In the case of our awkward Delete option from the last section (and therefore in others like it), the preventative approach would be simply to suppress the Delete button for products that may not be deleted. When you loaded records from the Products table into a DataSet, you could also query the Order Details table to see whether there were any order items for each product. However, you would then have to display the records in a customized data grid control because the standard DataGrid doesn't offer a way to display Delete buttons selectively.

  • A simpler approach here would be to check whether there are orders for a product when the page is posted back. This is less robust, because your users can ask to delete a product only to be told later that it can't be deleted, which may annoy them. If this is not a problem, though, you could perform such checking in the handler for the DeleteCommand event.

Try It Out - Validating a DataGrid Control

start example

The final exercise in this chapter will add some server-side error validation code to the ASP.NET page that we created in the previous exercise.

  1. First, add a Label control to the top of the page, and name it lblError:

     <form method="post" runat="server">   <asp:Label  runat="server" Width="164" /><br/><br/>   <asp:DataGrid  runat="server"                 CellPadding="5" AutoGenerateColumns="False"                 OnEditCommand="EditRecord"                 OnCancelCommand="CancelEdit"                 OnUpdateCommand="UpdateRecord"                 OnDeleteCommand="DeleteRecord">   <Columns> 

  2. If the user enters a negative or zero price value, this label will display an error message. Next, modify the UpdateRecord() function as follows.

     Public Sub UpdateRecord(ByVal Sender As Object,                         ByVal E As DataGridCommandEventArgs)   ' Retrieve the field values in the edited row   Dim ProductID As Int32 = Convert.ToInt32(E.Item.Cells(0).Text)   Dim PriceTextBox As TextBox = CType(E.Item.Cells(2).Controls(0), TextBox)   Dim Price As Decimal = Convert.ToDecimal(PriceTextBox.Text)   If Price > 0 Then     dgProducts.EditItemIndex = -1     lblError.Visible = False     UpdateProduct(ProductID, Price)   Else     LoadGrid()     With lblError       .Text = "Product price must be greater than 0"       .ForeColor = Drawing.Color.Red       .Visible = True     End With   End If End Sub 

  3. With these changes in place, any attempt to update a price with a value that's not sensible will result in a friendly error message:

    click to expand

end example

How It Works

Our code now checks whether the price entered is greater than 0. If so, it proceeds to update the product, just as before - but if not, it reloads the DataGrid with unchanged records, keeping the edit text box open (because the EditItemIndex property of the DataGrid is unchanged). In addition, as you saw, it displays an error message in the newly added Label control.



Beginning ASP. NET 2.0 and Databases
Beginning ASP.NET 2.0 and Databases (Wrox Beginning Guides)
ISBN: 0471781347
EAN: 2147483647
Year: 2004
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net