private void FormOrthoChart_FormClosing(object sender, FormClosingEventArgs e) { //Save data from grid to table for (int i = 0; i < gridMain.Rows.Count; i++) { table.Rows[i]["Date"] = gridMain.Rows[i].Tag; //store date for (int j = 0; j < listOrthDisplayFields.Count; j++) { table.Rows[i][j + 1] = gridMain.Rows[i].Cells[j + 1].Text; } } List <OrthoChart> tempOrthoChartsFromDB = OrthoCharts.GetAllForPatient(PatCur.PatNum); List <OrthoChart> tempOrthoChartsFromTable = new List <OrthoChart>(); for (int r = 0; r < table.Rows.Count; r++) { for (int c = 1; c < table.Columns.Count; c++) //skip col 0 { OrthoChart tempChart = new OrthoChart(); tempChart.DateService = (DateTime)table.Rows[r]["Date"]; tempChart.FieldName = listOrthDisplayFields[c - 1].Description; tempChart.FieldValue = table.Rows[r][c].ToString(); tempChart.PatNum = PatCur.PatNum; tempOrthoChartsFromTable.Add(tempChart); } } //Check table list vs DB list for inserts, updates, and deletes. for (int i = 0; i < tempOrthoChartsFromTable.Count; i++) { //Either delete an existing record from the DB or ignore this non-entry. if (tempOrthoChartsFromTable[i].FieldValue == "") { for (int j = 0; j < tempOrthoChartsFromDB.Count; j++) { if (tempOrthoChartsFromDB[j].DateService == tempOrthoChartsFromTable[i].DateService && tempOrthoChartsFromDB[j].FieldName == tempOrthoChartsFromTable[i].FieldName) { OrthoCharts.Delete(tempOrthoChartsFromDB[j].OrthoChartNum); break; } } continue; //i loop } //Update the Record if it already exists or Insert if it's new. for (int j = 0; j <= tempOrthoChartsFromDB.Count; j++) { //Insert if you've made it through the whole list. if (j == tempOrthoChartsFromDB.Count) { OrthoCharts.Insert(tempOrthoChartsFromTable[i]); break; } //Update if type and date match if (tempOrthoChartsFromDB[j].DateService == tempOrthoChartsFromTable[i].DateService && tempOrthoChartsFromDB[j].FieldName == tempOrthoChartsFromTable[i].FieldName) { tempOrthoChartsFromTable[i].OrthoChartNum = tempOrthoChartsFromDB[j].OrthoChartNum; OrthoCharts.Update(tempOrthoChartsFromTable[i]); break; } } } }