I searched for quite a while for an answer to this, but with no joy. All the answeres seem to be how to deal with getting a DBNull value out of a database, not to put it in . Perhaps I am not using the right search terms, but here we go.
Background:
I have a database with 2 tables with the following pertinent fields:
- EMPLOYEE
- EMPLOYEE_ID (pk) (string)
- VEHICLE
- VEHICLE_ID (pk) (int)
- EMPLOYEE_ID (fk) (string)
These are loaded up in to a typed data set called vEHICLE_MILEAGEDataSet
Inside of the VEHICLE table, the foreign key, EMPLOYEE_ID is nullable.
My problem is this: I want to be able to un-assign an employee from a vehicle, and to do that, I would set EMPLOYEE_ID to DBNull in the VEHICLE table getting the currently selected vehicle.
Here is my code to do this (with the unimportant bits taken out):
Expand|Select|Wrap|Line Numbers
- VEHICLE_MILEAGEDataSet.VEHICLERow vehRow = (employeeVehicleBindingSource.Current as DataRowView).Row as VEHICLE_MILEAGEDataSet.VEHICLERow;
- if (vehRow != null)
- {
- //Place a Null in the EmployeeID column for the current vehicle
- vehRow.EMPLOYEE_ID = DBNull.Value;
- }
- //commit the changes
- this.Validate();
- this.employeeVehicleBindingSource.EndEdit();
- this.vEHICLETableAdapter.Update(this.vEHICLE_MILEAGEDataSet.VEHICLE);
- //refresh the data
- this.vEHICLETableAdapter.Fill(this.vEHICLE_MILEAGEDataSet.VEHICLE);
I tried using DBNull.Value.ToString(); but I think that is sending an empty string, which wouldn't match any of the entries in the EMPLOYEE table, and give an constraints exception.
So how do I do this? It seems like it should be pretty simple, but it has me stumped.
Thanks,
-dan