Chapter 31
Private Const cCustomerType As String = “I”
Private Sub BindingNavigatorAddNewItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _
Handles BindingNavigatorAddNewItem.Click
Dim drv As DataRowView
‘Create record in the Customer table
drv = TryCast(Me.CustomerBindingSource.AddNew, DataRowView) If drv Is Nothing Then Return
Dim cr As AdventureWorksDataSet.CustomerRow = _
TryCast(drv.Row, AdventureWorksDataSet.CustomerRow)
If cr Is Nothing Then Return cr.rowguid = Guid.NewGuid cr.CustomerType = cCustomerType cr.ModifiedDate = Now
‘Create record in the Contact table
drv = TryCast(Me.ContactBindingSource.AddNew, DataRowView) If drv Is Nothing Then Return
Dim ct As AdventureWorksDataSet.ContactRow = _
TryCast(drv.Row, AdventureWorksDataSet.ContactRow)
If ct Is Nothing Then Return ct.NameStyle = True ct.PasswordSalt = “” ct.PasswordHash = “” ct.rowguid = Guid.NewGuid ct.ModifiedDate = Now
‘Create record in the Individual table
drv = TryCast(Me.IndividualBindingSource.AddNew, DataRowView) If drv Is Nothing Then Return
Dim indiv As AdventureWorksDataSet.IndividualRow =
TryCast(drv.Row, AdventureWorksDataSet.IndividualRow)
indiv.CustomerRow = cr indiv.ContactRow = ct indiv.ModifiedDate = Now
End Sub
From this example, it seems that you are unnecessarily setting some of the properties — for example, PasswordSalt and PasswordHash being equal to an empty string. This is necessary to ensure that the new row meets the constraints established by the database. Because these fields cannot be set by the user, you need to ensure that they are initially set to a value that can be accepted by the database. Clearly, for a secure application, the PasswordSalt and PasswordHash would be set to appropriate values.
Running the application with this method instead of the automatically wired event handler enables you to create a new Customer record using the Add button. If you enter values for each of the fields, you can save the changes.
Validation
In the previous section, you added functionality to create a new customer record. If you don’t enter appropriate data upon creating a new record — for example, you don’t enter a first name — this record will be rejected when you click the Save button. In fact, an exception will be raised if you try to move away from this record. The schema for the AdventureWorksDataSet contains a number of constraints, such as FirstName can’t be null, which are checked when you perform certain actions, such as saving or moving