private void BtnAddOrUpdateStudent_Click(object sender, EventArgs e) { // Object initialization syntax // could go property by property ex.. stu.Program = txtProgram.Text; // Assume all data is valid Student stu = new Student() { FirstName = txtFirstName.Text, LastName = txtLastName.Text, ProgramOfChoice = txtProgram.Text, DOB = dtpDateOfBirth.Value, }; try { if (existingStudent != null) { stu.StudentID = existingStudent.StudentID; StudentDB.Update(stu); MessageBox.Show("Student Updated!"); } else { StudentDB.Add(stu); MessageBox.Show("Student Added!"); } Close(); } catch (SqlException) // Didnt give variable name becasue it wasn't used. { MessageBox.Show("There was a DB Problem, Try again later."); } }
/// <summary> /// retrieves all students from db and puts in listbox /// </summary> private void PopulateStudentListBox() { List <Student> students = StudentDB.GetAllStudents(); students = students.OrderBy(stu => stu.FirstName).ToList(); lstStudents.Items.Clear(); foreach (Student s in students) { lstStudents.Items.Add(s).ToString(); //lstStudents.Items.Add($"{s.FirstName} {s.LastName}"); } }
private void btnDeleteStudent_Click(object sender, EventArgs e) { if (lstStudents.SelectedIndex < 0) { MessageBox.Show("Please choose a student"); return; } Student stu = lstStudents.SelectedItem as Student; string msg = $"Are you sure you want to delete" + $"{stu.StudentID} : {stu.FullName}"; DialogResult answer = MessageBox.Show(msg, "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (answer == DialogResult.Yes) { StudentDB.Delete(stu.StudentID); PopulateStudentListBox(); MessageBox.Show("Student Deleted Successfully."); } }