You need to use .FirstOrDefault and check whether a valid entity has been found:
//select row to delete
Doctor del = ((Doctor)cbDocIdd.SelectedItem);
Doctor deleted = (from d in MainWindow.nlh.Doctors
where d.DoctorID == del.DoctorID
select d).FirstOrDefault();
// check if it even exists!!
if(deleted != null)
{
//delete row from db
MainWindow.nlh.Doctors.DeleteObject(deleted);
//Save to database
MainWindow.nlh.SaveChanges();
MessageBox.Show("Doctor deleted");
this.Close();
}
If you use .First() and the doctor with that given ID doesn't exist, you'll get an exception
Also: make sure the del value is OK and not null before using it in the following statement. Same goes for MainWindow - are you sure this is not null ??
Update: can you try these two lines and tell me what the result is??
//select row to delete
object selectedObj = cbDocIdd.SelectedItem;
if(selectedObj != null)
{
string typeOfSelectedObj = selectedObj.GetType().Name;
}
Doctor del = ((Doctor)cbDocIdd.SelectedItem);
Is selectedObj something other than null?? And if so: what type is it??
Update #2: Ok - so the doctor does exist and is being returned OK - can you try this for me??
Replace this line:
Doctor del = ((Doctor)cbDocIdd.SelectedItem);
with this instead:
Doctor del = cbDocIdd.SelectedItem as Doctor;
When you run this - is del now something other than null ?
Solution:
In the end, the real reason why this code broke lies in the fact that the call to MainWindow.nlh.Doctors.DeleteObject(deleted); caused an event handler to fire, which included this code:
private void cbDocIdd_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// populate with DoctorID from db
Doctor deletedDoc = ((Doctor)cbDocIdd.SelectedItem);
tbLastName.Text = deletedDoc.LastName.ToString();
tbFirstName.Text = deletedDoc.FirstName.ToString();
tbLicenseNumber.Text = deletedDoc.LicenseNumber.ToString();
}
but in this situation, when a doctor is being deleted, the deletedDoc was returned as NULL, but no check is in place to ensure to access only a non-NULL object ..... therefore, an infamous "null-reference exception" was thrown when trying to access the deletedDoc.LastName property...