Aracılığıyla paylaş


How to: Add Validation to an N-Tier Dataset

Adding validation to a dataset that is separated into an n-tier solution is basically the same as adding validation to a single-file dataset (a dataset in a single project). The suggested location for performing validation on data is during the ColumnChanging and/or RowChanging events of a data table.

The Dataset Designer provides the functionality to create partial classes to which you can add user code to column and row changing events of the data tables in the dataset. For more information about adding code to a dataset in an n-tier solution, see How to: Add Code to Datasets in N-Tier Applications, and How to: Add Code to TableAdapters in N-Tier Applications. For more information about partial classes, see How to: Split a Class into Partial Classes or Partial Classes and Methods (C# Programming Guide).

Note

When you separate datasets from TableAdapters (by setting the DataSet Project property), existing partial dataset classes in the project will not be moved automatically. Existing dataset partial classes must be moved manually to the dataset project.

Note

The Dataset Designer does not automatically create event handlers in C# for the ColumnChanging and RowChanging events. You have to manually create an event handler and hook the event handler up to the underlying event. The following procedures provide the steps to create the required event handlers in both Visual Basic and C#.

Validating Changes to Individual Columns

Validate values in individual columns by handling the ColumnChanging event. The ColumnChanging event is raised when the value in a column is modified. Create an event handler for the ColumnChanging event by double-clicking the desired column on the Dataset Designer.

The first time that you double-click a column, the designer generates an event handler for the ColumnChanging event. In addition to the ColumnChanging event, an If…Then statement is also created that tests for the specific column. For example, the following code is generated when the RequiredDate column on the Northwind Orders table is double clicked:

Private Sub OrdersDataTable_ColumnChanging(ByVal sender As System.Object, ByVal e As System.Data.DataColumnChangeEventArgs) Handles Me.ColumnChanging
    If (e.Column.ColumnName = Me.RequiredDateColumn.ColumnName) Then
        ' Add validation code here.
    End If
End Sub

Note

In C# projects, the Dataset Designer only creates partial classes for the dataset and individual tables in the dataset. The Dataset Designer does not automatically create event handlers for the ColumnChanging and RowChanging events in C# like it does in Visual Basic. In C# projects, you have to manually construct a method to handle the event and hook the method up to the underlying event. The following procedure provides the steps to create the required event handlers in both Visual Basic and C#.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To add validation during changes to individual column values

  1. Open the dataset in the Dataset Designer by double-clicking the .xsd file in Solution Explorer. For more information, see How to: Open a Dataset in the Dataset Designer.

  2. Double-click the column you want to validate. This action creates the ColumnChanging event handler.

    Note

    The Dataset Designer does not automatically create an event handler for the C# event. The code necessary to handle the event in C# is included below. SampleColumnChangingEvent is created and then it is hooked up to the ColumnChanging event in the EndInit method.

  3. Add code to verify that e.ProposedValue contains data that meets the requirements of your application. If the proposed value is unacceptable, set the column to indicate that it contains an error.

    The following code example validates that the Quantity column contains more than 0. If the Quantity is less than or equal to 0, the column is set to an error. The Else clause clears the error if the quantity is more than 0. The code in the column-changing event handler should resemble the following:

    If (e.Column.ColumnName = Me.QuantityColumn.ColumnName) Then
        If CType(e.ProposedValue, Short) <= 0 Then
            e.Row.SetColumnError(e.Column, "Quantity must be greater than 0")
        Else
            e.Row.SetColumnError(e.Column, "")
        End If
    End If
    
    // C#
    // Add this code to the DataTable 
    // partial class.
    
        public override void EndInit()
        {
            base.EndInit();
            // Hook up the ColumnChanging event
            // to call the SampleColumnChangingEvent method.
            ColumnChanging += SampleColumnChangingEvent;
        }
    
        public void SampleColumnChangingEvent(object sender, System.Data.DataColumnChangeEventArgs e)
        {
            if (e.Column.ColumnName == QuantityColumn.ColumnName)
            {
                if ((short)e.ProposedValue <= 0)
                {
                    e.Row.SetColumnError("Quantity", "Quantity must be greater than 0");
                }
                else
                {
                    e.Row.SetColumnError("Quantity", "");
                }
            }
        }
    

Validating Changes to Whole Rows

Validate values in whole rows by handling the RowChanging event. The RowChanging event is raised when the values in all columns are committed. It is necessary to validate in the RowChanging event when the value in one column relies on the value in another column. For example, consider OrderDate and RequiredDate in the Orders table in Northwind. When orders are being entered, validation makes sure that an order is not entered with a RequiredDate that is on or before the OrderDate. In this example, the values for both the RequiredDate and OrderDate columns need to be compared, so validating an individual column change does not make sense.

Create an event handler for the RowChanging event by double-clicking the table name in the title bar of the table on the Dataset Designer.

To add validation during changes to whole rows

  1. Open the dataset in the Dataset Designer by double-clicking the .xsd file in Solution Explorer. For more information, see How to: Open a Dataset in the Dataset Designer.

  2. Double-click the title bar of the data table on the designer.

    A partial class is created with a RowChanging event handler and opens in the Code Editor.

    Note

    The Dataset Designer does not automatically create an event handler for the RowChanging event in C# projects. You have to create a method to handle the RowChanging event and execute code to hook up the event in the table's initialization method.

  3. Add user code inside the partial class declaration.

  4. The following code shows where to add user code to validate during the RowChanging event for Visual Basic:

    Partial Class OrdersDataTable
        Private Sub OrdersDataTable_OrdersRowChanging(ByVal sender As System.Object, ByVal e As OrdersRowChangeEvent) Handles Me.OrdersRowChanging
            ' Add logic to validate columns here.
            If e.Row.RequiredDate <= e.Row.OrderDate Then
                ' Set the RowError if validation fails.
                e.Row.RowError = "Required Date cannot be on or before the OrderDate"
            Else
                ' Clear the RowError when validation passes.
                e.Row.RowError = ""
            End If
        End Sub
    End Class
    
  5. The following code shows how to create the RowChanging event handler and where to add user code to validate during the RowChanging event for C#:

    partial class OrdersDataTable
    {
        public override void EndInit()
        {
            base.EndInit();
            // Hook up the event to the
            // RowChangingEvent method.
            OrdersRowChanging += RowChangingEvent;
        }
    
        public void RowChangingEvent(object sender, OrdersRowChangeEvent e)
        {
            // Perfom the validation logic.
            if (e.Row.RequiredDate <= e.Row.OrderDate)
            {
                // Set the row to an error when validation fails.
                e.Row.RowError = "Required Date cannot be on or before the OrderDate";
            }
            else
            {
                // Clear the RowError if validation passes.
                e.Row.RowError = "";
            }
        }
    }
    

See Also

Tasks

Walkthrough: Creating an N-Tier Data Application

Concepts

What's New in Data

Creating Data Applications by Using Visual Studio

N-Tier Data Application Overview

Data Validation Overview