Blogs

Paul Kimmel's Blog

Validating Rows in the ASPxGridView

     

Row validation is built into the ASPxGridView. You don’t have to manually add .NET validators, graphics, or placeholders for text with the ASPxGridView. To validate a grid row all you have to do is look at the data and provide the feedback in the event of an error. As I am awaiting for my author copies of Professional DevExpress ASP.NET Controls—I have books promised—I am poking around and plumbing the ASP.NET controls and their many members for interesting aspects and interesting ways to present them.

This blog shows you how to use the DoRowValidation method to validate a row of data in the ASPxGridView. The sub-sections contain the complete steps for getting data into the grid, supporting editing the data, and validating the contents of the grid cells. If you are brand new to the ASPxGridView then read all of the sections. If you know how to get data into the ASPxGridView using declarative code and enable editing then skip to the last section  for the DoRowValidation part.

Binding Data to an ASPxGridView

Using wizards and designers to generate declarative statements isn’t fundamentally good or bad. Some programmers like control and can write ASP.NET code blindfolded without a mistake. Using a designer to write code for you and letting the data binding and all of the plumbing be managed for you is good in that it saves you time writing code and debugging.

The fastest way to get data into an ASPxGridView is to drop an ASPxGridView onto a Web page and click on Choose Data Source|<New data source> from the ASPxGridView’s smart tags menu. Walk through the Configure Data Source wizard following the numbered steps and using the associated figures as a guide.

  1. In the Choose Your Data Source Connection step click New Connection or pick an existing connection from the dropdown list (see Figure 1)
  2. Click Next
  3. In the Configure Select Statement step—see Figure 2—check specify columns from a table or view
  4. Pick the Customers table and click the asterisk for all columns
  5. In the same step click the Advanced button to display the Advanced SQL Generation Options and check the Generate INSERT, UPDATE, and DELETE statements—see Figure
  6. Click OK
  7. Click Next
  8. On the Test Query step click Finish

image
Figure 1: Pick an existing connection or configure a new connection.

image
Figure 2: Configure the declarative queries.

 image
Figure 3: Use the Advanced SQL Generation option dialog to generate all of the SQL CRUD commands.  

The numbered steps add a lot of attributes and some declarative SQL to the ASP.NET code. Listing 1 shows you the ASP.NET.

Listing 1: The ASP.NET with all of the attributes and SQL that eliminates the need for imperative code—hand-written code.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Register assembly="DevExpress.Web.ASPxGridView.v9.2, Version=9.2.8.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" namespace="DevExpress.Web.ASPxGridView" tagprefix="dxwgv" %>
<%@ Register assembly="DevExpress.Web.ASPxEditors.v9.2, Version=9.2.8.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" namespace="DevExpress.Web.ASPxEditors" tagprefix="dxe" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <dxwgv:ASPxGridView ID="ASPxGridView1" runat="server"
        AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
        KeyFieldName="CustomerID">
        <Columns>
          <dxwgv:GridViewDataTextColumn FieldName="CustomerID" ReadOnly="True"
            VisibleIndex="0">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="CompanyName" VisibleIndex="1">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="ContactName" VisibleIndex="2">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="ContactTitle" VisibleIndex="3">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="Address" VisibleIndex="4">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="City" VisibleIndex="5">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="Region" VisibleIndex="6">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="PostalCode" VisibleIndex="7">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="Country" VisibleIndex="8">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="Phone" VisibleIndex="9">
          </dxwgv:GridViewDataTextColumn>
          <dxwgv:GridViewDataTextColumn FieldName="Fax" VisibleIndex="10">
          </dxwgv:GridViewDataTextColumn>
        </Columns>
      </dxwgv:ASPxGridView>
      <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
        DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = @CustomerID"
        InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax]) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle, @Address, @City, @Region, @PostalCode, @Country, @Phone, @Fax)"
        SelectCommand="SELECT * FROM [Customers]"
        UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [ContactName] = @ContactName, [ContactTitle] = @ContactTitle, [Address] = @Address, [City] = @City, [Region] = @Region, [PostalCode] = @PostalCode, [Country] = @Country, [Phone] = @Phone, [Fax] = @Fax WHERE [CustomerID] = @CustomerID">
        <DeleteParameters>
          <asp:Parameter Name="CustomerID" Type="String" />
        </DeleteParameters>
        <UpdateParameters>
          <asp:Parameter Name="CompanyName" Type="String" />
          <asp:Parameter Name="ContactName" Type="String" />
          <asp:Parameter Name="ContactTitle" Type="String" />
          <asp:Parameter Name="Address" Type="String" />
          <asp:Parameter Name="City" Type="String" />
          <asp:Parameter Name="Region" Type="String" />
          <asp:Parameter Name="PostalCode" Type="String" />
          <asp:Parameter Name="Country" Type="String" />
          <asp:Parameter Name="Phone" Type="String" />
          <asp:Parameter Name="Fax" Type="String" />
          <asp:Parameter Name="CustomerID" Type="String" />
        </UpdateParameters>
        <InsertParameters>
          <asp:Parameter Name="CustomerID" Type="String" />
          <asp:Parameter Name="CompanyName" Type="String" />
          <asp:Parameter Name="ContactName" Type="String" />
          <asp:Parameter Name="ContactTitle" Type="String" />
          <asp:Parameter Name="Address" Type="String" />
          <asp:Parameter Name="City" Type="String" />
          <asp:Parameter Name="Region" Type="String" />
          <asp:Parameter Name="PostalCode" Type="String" />
          <asp:Parameter Name="Country" Type="String" />
          <asp:Parameter Name="Phone" Type="String" />
          <asp:Parameter Name="Fax" Type="String" />
        </InsertParameters>
      </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Enabling Edits in the ASPxGridView

The first pre-requisite for editing in the ASPxGridView is that you need declarative (or imperative) code that supports the edits. The next step is to turn on the edit metaphors in the ASPxGridView. To enable editing—inserting and editing—click on the ASPxGridView’s smart tags menu and check Enable Editing and Enable Inserting.

Setting these options will add a GridViewCommandColumn to the grid and display the Edit and New link buttons—see Figure 4. Clicking these buttons will place the grid in edit mode and display an Update and Cancel link while the grid is edit mode. All of this behavior—insert, new, update, and cancel—is supported automatically. You don’t have to write any code because the grid will interact with the declarative SQL statements to manage the edits for you.

image
Figure 4: The GridViewCommandColumn can be seen in the left-most column.

Implementing Row Validation

To prepare for row validation select the ASPxGridView control and implement stubs for the RowValidating and StartRowEditing events. When the grid is placed in edit mode the StartRowEditing event will be raised from there you can kick off custom row validation by calling DoRowValidation and implementing the custom validation code in the RowValidating event handler. Listing 2 shows the coordination between the events. Listing 3 provides the implementation of the extension method that actually does the validation. (I don’t like cluttered Web code-behind so often move this kind of code out of the page.)

Listing 2: The code-behind that shows the coordination between the StartRowEditing and RowValidating event handlers.

Partial Class _Default
    Inherits System.Web.UI.Page

  Protected Sub ASPxGridView1_StartRowEditing(ByVal sender As Object, _
    ByVal e As DevExpress.Web.Data.ASPxStartRowEditingEventArgs) _
    Handles ASPxGridView1.StartRowEditing

    If (Not ASPxGridView1.IsNewRowEditing) Then
      ASPxGridView1.DoRowValidation()
    End If

  End Sub

  Protected Sub ASPxGridView1_RowValidating(ByVal sender As Object, _
    ByVal e As DevExpress.Web.Data.ASPxDataValidationEventArgs) _
    Handles ASPxGridView1.RowValidating

    ASPxGridView1.Columns.Iterate(e)

  End Sub
End Class

Listing 3: The extension method Iterate extends the GridViewColumnCollection and provides basic field validation.

Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices
Imports DevExpress.Web.ASPxGridView
Imports DevExpress.Web.Data

Public Module Iterator
  <Extension()> _
  Public Sub Iterate(ByVal columns As GridViewColumnCollection, _
                           ByVal e As ASPxDataValidationEventArgs)

    For Each column As GridViewColumn In columns
      If (column Is Nothing) Then Continue For

      If (TypeOf column Is GridViewDataColumn = False) Then Continue For
      Dim temp As GridViewDataColumn = CType(column, GridViewDataColumn)

      If (e.NewValues(temp.FieldName) Is Nothing) Then
        e.Errors(temp) = "Value cannot be null"
      End If
    Next
  End Sub

End Module

In the example the Iterate method makes sure the individual fields are not null. Of course, it may be permissible for some fields to be null and other kinds of fields may need additional validation. There is a GridViewDataColumn child class for the various field data types. For example, for date fields there is a GridViewDataDateColumn. You can check the GridViewDataxxxx type to help you determine which kinds of validation to perform on individual fields.

If there is an error then place the error in the ASPxDataValidationEventArgs.Errors property which is a Dictionary. Error text placed in the Errors property is represented in the ASPxGridView as an icon. Float the cursor over the icon and you will see your error text (Refer to Figure 5).

image
Figure 5: Based on the basic validation the Region field is null and an error icon and text are placed adjacent to the Region’s edit control.

StartRowEditing is called when you click the Insert button. StartRowEditing in the example calls DoRowValidation, which in turn fires the RowValidating event. When you click Update the RowValidating event fires naturally.

Summary

There are a lot of members in a big control like the ASPxGridView. Getting data in an ASPxGridView is easy. Figuring out how to use the dozens of members takes a little more time. That’s what we are here for. Happy Programming!

Published Nov 06 2009, 05:31 PM by Paul Kimmel (DevExpress)
Bookmark and Share

Comments

No Comments
More from DevExpress
Live Chat
Have a pre-sales question?
Need assistance with your evaluation?
We are here to help.
Chat is one of the many ways you can contact members of the DevExpress Team. We are available Monday-Friday between 8:30am and 5:00pm Pacific Time.
If you need additional product information, require pre-sales assistance, or want help with your order, write to us at info@devexpress.com or call us at
+1 (818) 844-3383.