private void simpleButtonMergeDiagnosis_Click(object sender, EventArgs e) { var itemsSelected = listBoxDiagnosis.SelectedItems; if (itemsSelected.Count > 1) { SplashScreenManager.ShowForm(this, typeof(WaitForm1), true, true, false); try { using (var context = new LorikeetAppEntities()) { var dr = new DialogResult(); var form = new FormInput(); dr = form.ShowDialog(); if (dr == DialogResult.OK) { var diagnosisToAdd = new DiagnosisName(); diagnosisToAdd.DiagnosisName1 = form.inputText; context.DiagnosisNames.Add(diagnosisToAdd); context.SaveChanges(); int i = diagnosisToAdd.DiagnosisNameID; for (int x = 0; x < itemsSelected.Count - 1; x++) { string diagnosisString = itemsSelected[x].ToString(); var diagnosisToUpdate = (from d in context.Diagnosis join dn in context.DiagnosisNames on d.DiagnosisNameID equals dn.DiagnosisNameID where dn.DiagnosisName1 == diagnosisString select d).ToList(); if (diagnosisToUpdate.Any()) { foreach (var dtu in diagnosisToUpdate) { dtu.DiagnosisNameID = i; context.SaveChanges(); } } } foreach (var item in itemsSelected) { string itemString = item.ToString(); var diagnosisNamesToRemove = (from dn in context.DiagnosisNames where dn.DiagnosisName1 == itemString select dn).ToList(); if (diagnosisNamesToRemove.Any()) { foreach (var dmtr in diagnosisNamesToRemove) { context.DiagnosisNames.Remove(dmtr); } context.SaveChanges(); } } } else { return; } } } catch (Exception ex) { MessageBox.Show(MiscStuff.GetAllMessages(ex)); } SplashScreenManager.CloseForm(); } else { MessageBox.Show("You must select at least 2 items"); } RefreshListBoxes(); }