Problem: I am using C# to create a (hopefully) simple UI to access data stored in 1 table. I created the DataSource and a DataGrid. I then dropped the datasource on the grid and Visual Studio helpfully created all the controls that I need. However, the table contains columns that do not allow null. How can I trap the fact that an inserted row contains a column with a null value

Thank you in advance.

Re: .NET Framework Data Access and Storage Data validation prior to an INSERT statement.

Derek Smyth


Good question and unfortunately it all depends on where you want to validate the data. For example you can trap the error at the table (data) level or you can trap the error at the grid (user interface) level. General rule of thumb is to trap this sort of error at the user interface level.

The best datagrid event, and there are a few to choose from, to handle the validation would be the Row_Validating event. This looks to occur just before the row is submitted to the table. In this event you can check all the entered values for null and cancel the addition.

I'm really sorry this in VB.NET, I was working off an older example...

Private Sub AddressDataGridView_RowValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles AddressDataGridView.RowValidating

For Each currentCell As DataGridViewCell In AddressDataGridView.Rows(e.RowIndex).Cells

If currentCell.Value Is DBNull.Value Then

e.Cancel = True

End If


End Sub

Hopefully the example code just demonstrates that you iterate each of the cell in the dataviewgrids current row and check if the current cells value is DBNull.Value (and not null). e.Cancel stops the row from being commited to the table.

Re: .NET Framework Data Access and Storage Data validation prior to an INSERT statement.


Thank you. This pointed me to what I needed ... the Row_Validating event.

Much appreciated.