protected void btnSave_Click(object sender, EventArgs e) { // Use EF to connect to SQL Server using (WorkoutEntities db = new WorkoutEntities()) { // Use the Student Model to save the new record Workout w = new Workout(); Int32 WorkoutID = 0; // Check the QueryString for an ID so we can determine add / update if (Request.QueryString["WorkoutID"] != null) { // Get the ID from the URL WorkoutID = Convert.ToInt32(Request.QueryString["WorkoutID"]); // Get the current student from the Enity Framework w = (from objW in db.Workouts where objW.WorkoutID == WorkoutID select objW).FirstOrDefault(); } w.WorkoutName = txtName.Text; w.WorkoutType = ddlType.SelectedValue; if (ddlType.SelectedValue == "Strength") { w.WorkoutWeight = Convert.ToInt32(txtWeight.Text); w.WorkoutSets = Convert.ToInt32(txtSets.Text); w.Reps = Convert.ToInt32(txtReps.Text); } w.WorkoutTime = Convert.ToDecimal(txtLength.Text); w.TimeCompleted = Convert.ToDateTime(calTime.SelectedDate); // Call add only if we have no student ID if (WorkoutID == 0) { db.Workouts.Add(w); } db.SaveChanges(); // Redirect to the updated students page Response.Redirect("/exercises.aspx"); } }
protected void grdExercises_RowDeleting(object sender, GridViewDeleteEventArgs e) { // Store which row was clicked Int32 selectedRow = e.RowIndex; // Get the selected WorkoutID using the grid's Data Key collection Int32 WorkoutID = Convert.ToInt32(grdExercises.DataKeys[selectedRow].Values["WorkoutID"]); try { // Use Enity Framework to remove the selected Workout from the DB using (WorkoutEntities db = new WorkoutEntities()) { Workout w = (from objW in db.Workouts where objW.WorkoutID == WorkoutID select objW).FirstOrDefault(); // Using First would get an error if no data comes back, FirstOrDefault won't throw an error // Do the delete db.Workouts.Remove(w); db.SaveChanges(); } } catch (Exception ex) { Response.Redirect("/error.aspx"); } // Refresh the grid GetWorkouts(); }