Windows Forms DataGrid Control in VB.NET
In this article you will learn how to Validate Input with the Windows Forms DataGrid Control
There are two types of input validation
available for the Windows Forms DataGrid control. If the
user attempts to enter a value that is of an unacceptable data type for the
cell, for example a string into an integer, the new invalid value is
replaced with the old value. This kind of input validation is done
automatically and cannot be customized.
The other type of input validation
can be used to reject any unacceptable data, for example a zero value in a field
that must be greater than or equal to one, or an inappropriate string. This is
done in the dataset by writing an event handler for the
DataTable.RowChanging event. The example below uses the
ColumnChanging event because the unacceptable value is disallowed for
the "Product" column in particular. You might use the RowChanging
event for checking that the value of an "End Date" column is later than the
"Start Date" column in the same row.
validate user input
Write code to handle the
ColumnChanging event for the appropriate table. When
inappropriate input is detected, call the SetColumnError
method of the DataRow object.
' Only check for errors in the
' Do not allow
"Automobile" as a product.
e.ProposedValue = "Bad
"The Product column contians an error"
"Product cannot be " & _
Connect the event handler to the event.
Place the following code
within either the form's Load event or its constructor.
' Assumes the grid is bound to a dataset called
' with a table called Customers.
' Put this code in the form's Load
event or its constructor.