| Main ASP .NET Tutorial Index |
Scott Mitchell June 2006 Download the ASPNET_Data_Tutorial_2_CS.exe sample code. Contents of Tutorial 2 (Visual C#)
Introduction Step 3: Adding Field-Level Validation to the DataRow ClassesField-level validation are checks that pertains to the property values of the business objects when inserting or updating. Some field-level validation rules for products include:
These rules can and should be expressed at the
database level. The character limit on the In addition to enforcing these rules at the
database they should also be enforced at the DataSet
level. In fact, the field length and whether a value
is required or optional are already captured for
each DataTable's set of DataColumns. To see the
existing field-level validation automatically
provided, go to the DataSet Designer, select a field
from one of the DataTables and then go to the
Properties window. As Figure 4 shows, the
Figure 4. The DataColumn Provides Basic Field-Level Validation Unfortunately, we can't specify bounds checks,
such as the
Figure 5. Add a New Class to the
Next, create an event handler for the ProductsDataTable.ColumnChanging.cs public partial class Northwind
{
public partial class ProductsDataTable
{
public override void BeginInit()
{
this.ColumnChanging += ValidateColumn;
}
void ValidateColumn(object sender, DataColumnChangeEventArgs e)
{
if(e.Column.Equals(this.UnitPriceColumn))
{
if(!Convert.IsDBNull(e.ProposedValue) && (decimal)e.ProposedValue < 0)
{
throw new ArgumentException("UnitPrice cannot be less than zero", "UnitPrice");
}
}
else if (e.Column.Equals(this.UnitsInStockColumn) ||
e.Column.Equals(this.UnitsOnOrderColumn) ||
e.Column.Equals(this.ReorderLevelColumn))
{
if (!Convert.IsDBNull(e.ProposedValue) && (short)e.ProposedValue < 0)
{
throw new ArgumentException(string.Format("{0} cannot be less than zero", e.Column.ColumnName), e.Column.ColumnName);
}
}
}
}
}
Go to top of page or next part of tutorial |
||||


