Export (0) Print
Expand All

Validating Data During Column Changes

You can validate data when the column changes by responding to the ColumnChanging event. This event passes an event argument object with properties that give you access to the column being changed. Validation can also be performed during the RowChanging event, For more information see Validating Data During Row Changes.

To validate when a column changes

  1. Create an event handler for the ColumnChanging event of a data table. For more information, see Writing Event Handlers (Visual Basic) or Events Tutorial (C#).
  2. In the event handler, you can return the proposed and original values by examining the ProposedValue and Row properties:
    ' Visual Basic
    Dim newValue As String = CType(e.ProposedValue, String)
    Dim origvalue As String = CType(e.Row(e.Column), String)
    
    // C#
    string newValue = (string)e.ProposedValue;
    string origValue = (string)(e.Row[e.Column]);
    
  3. To get information about the column that is changing, examine the Column property that is passed to the handler:
    ' Visual Basic
    Dim colDataType As String = e.Column.DataType.ToString()
    Dim colName As String = e.Column.ColumnName
    
    // C#
    string colDataType = e.Column.DataType.ToString();
    string colName = e.Column.ColumnName;
    
  4. To reject the change, throw an exception.
    ' Visual Basic
    ' Throw the exception within the ColumnChanging event handler – 
    ' in this case we will validate for a value that is < 10.
    
    Private Sub dt_ColumnChanging(ByVal sender As Object, ByVal e As System.Data.DataColumnChangeEventArgs) Handles dt.ColumnChanging
       Dim newvalue As Integer = CType(e.ProposedValue, Integer)
       If newvalue < 10 Then
          MessageBox.Show(newvalue.ToString() & " is not less than 10")
          Throw New Exception(newvalue.ToString() & " is not less than 10")
       End If
    End Sub
    // C#
    private void dt_ColumnChanging(object sender, System.Data.DataColumnChangeEventArgs e)
    {
       int newvalue = (int)(e.ProposedValue);
       if (newvalue < 10) 
       {
          MessageBox.Show(newvalue.ToString() + " is not less than 10");
          throw new Exception(newvalue.ToString() + 
             " is not less than 10");
       }
    }
    

See Also

Dataset Updates in Visual Studio .NET | Introduction to Validating User Input in Web Forms | Validating Data During Row Changes | DataTable.ColumnChanging Event | DataTable.RowChanging Event | DataColumn Properties | Data Validation in Datasets | Writing Event Handlers (Visual Basic) | Events Tutorial (C#)

Show:
© 2015 Microsoft