private void saveGroups() { SchoolJournalEntities context = new SchoolJournalEntities(); var groupIDs = from g in context.Groups select g.GroupID; try { foreach (DataGridViewRow r in GroupsDataGridView.Rows) { if (r.IsNewRow) { continue; } int groupID = int.Parse(GroupsDataGridView["GroupID", r.Index].Value.ToString()); if (groupIDs.Contains(groupID)) //update { GroupDAL.UpdateGroup(groupID, int.Parse(GroupsDataGridView["TeacherID", r.Index].Value.ToString()), GroupsDataGridView["Subject", r.Index].EditedFormattedValue.ToString(), GroupsDataGridView["Grade", r.Index].EditedFormattedValue.ToString(), GroupsDataGridView["Description", r.Index].Value.ToString()); } else //add new { GroupsDataGridView["GroupID", r.Index].Value = GroupDAL.NewGroup(int.Parse(GroupsDataGridView["TeacherID", r.Index].Value.ToString()), GroupsDataGridView["Subject", r.Index].EditedFormattedValue.ToString(), GroupsDataGridView["Grade", r.Index].EditedFormattedValue.ToString(), GroupsDataGridView["Description", r.Index].Value.ToString()); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { context.Dispose(); } }