72
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SchoolSystem { // Written by : Paul Smyth // Date of last issue : 9/9/2015 // // This is the logon screen. It takes a user ID and a password from the user // and checks it against the data stored in the Teachers / Administration tables. // public partial class LogonForm : Form { SchoolDataClassesDataContext DB = new SchoolDataClassesDataContext (); //This variable defines the menu access option based on the Person Type public static string personType = "" ; // This variable stores the user ID so that it can be used // elsewhere in the program public static string personID = "" ; public LogonForm() { InitializeComponent(); } private void btnExit_Click( object sender, EventArgs e) { Application .Exit(); } private void btnLogon_Click( object sender, EventArgs e) { try { // look up ID in Persons database and test to see if the // one entered is valid. If valid, return the Type value // so that the password can be checked. var loginTest = ( from i in DB.Persons where i.ID == Int32 .Parse(txtUserID.Text) select i.Type).First(); if (loginTest == "Administrator" ) { // lookup password from Administrator file var passwordTest = ( from p in DB.Administrations

School System C# Code

Embed Size (px)

Citation preview

Page 1: School System C# Code

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace SchoolSystem{ // Written by : Paul Smyth // Date of last issue : 9/9/2015 // // This is the logon screen. It takes a user ID and a password from the user // and checks it against the data stored in the Teachers / Administration tables. //

public partial class LogonForm : Form { SchoolDataClassesDataContext DB = new SchoolDataClassesDataContext();

//This variable defines the menu access option based on the Person Type public static string personType = "";

// This variable stores the user ID so that it can be used // elsewhere in the program public static string personID = "";

public LogonForm() { InitializeComponent(); }

private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); }

private void btnLogon_Click(object sender, EventArgs e) { try { // look up ID in Persons database and test to see if the // one entered is valid. If valid, return the Type value // so that the password can be checked. var loginTest = (from i in DB.Persons where i.ID == Int32.Parse(txtUserID.Text) select i.Type).First();

if (loginTest == "Administrator") { // lookup password from Administrator file var passwordTest = (from p in DB.Administrations where p.AID == Int32.Parse(txtUserID.Text) select p.Password).First(); if (passwordTest == txtPassword.Text) { //lblMessage.Text = "Password is correct"; // Open the Main Menu Form for Administrators personType = "Administrator"; // sets up the main menu for administrators personID = txtUserID.Text; // used in the changePasssword form this.Hide(); //Hide the logon form

Page 2: School System C# Code

MainMenuForm administratorMainMenuForm = new MainMenuForm(); administratorMainMenuForm.ShowDialog(); clearFields(); this.Show(); // show the logon form when user logs off } else { lblMessage.Text = "Password is incorrect"; clearFields(); } } else if (loginTest == "Teacher") { // lookup password from Teacher file var passwordTest = (from p in DB.Teachers where p.TID == Int32.Parse(txtUserID.Text) select p.Password).First(); if (passwordTest == txtPassword.Text) { // Open the Main Menu Form for Teachers personType = "Teacher"; // sets up the main menu for teachers personID = txtUserID.Text; // used in the changePasssword form this.Hide(); //Hide the logon form MainMenuForm teacherMainMenuForm = new MainMenuForm(); teacherMainMenuForm.ShowDialog(); clearFields(); this.Show(); // show the logon form when user logs off } else { lblMessage.Text = "Password is incorrect"; clearFields(); } } else { lblMessage.Text = "Customer ID is invalid. Please contact your Data Administrator."; } }

catch (Exception) { lblMessage.Text = "Customer ID is invalid. Please contact your Data Administrator."; } }

private void LogonForm_Load(object sender, EventArgs e) { lblMessage.Text = "Please enter a valid User ID and Password.\r\nClick Logon or press Enter to continue.\r\nClick Exit to Quit."; clearFields(); } public void clearFields() { //Clear the text entry areas and prepare the login form a fresh entry txtUserID.Clear(); txtPassword.Clear(); txtUserID.Select(); } }}

Page 3: School System C# Code

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace SchoolSystem{ //Written by : Paul Smyth //Date of last issue : 9/9/2015 // // This form sets up the Main Menu which allows the user to // navigate the key functions of the software. // // It takes the static variable personType from the logonForm // to indicate if the user is a teacher or administrator. It // uses this variable to switch on the menu items the user has // access to. // public partial class MainMenuForm : Form { // Holds the user selection which will be used // in the chosen Form selected from this menu. // It will either be Student, Teacher or Administrator // depending on the user choice.

public static string MenuChoice = "";

public MainMenuForm() { InitializeComponent(); }

private void MainMenuForm_Load(object sender, EventArgs e) {

// Update the form header this.Text = LogonForm.personType + " Menu";

lblMainMenuMessage.Text = "Click on an option"; // Set up which button options will be available for Teacher if (LogonForm.personType == "Teacher") { btnCourses.Enabled = true; btnQualifications.Enabled = true; btnMarks.Enabled = true; btnTeachers.Enabled = false; btnStudents.Enabled = false; btnAdministrators.Enabled = false; btnChangePassword.Enabled = true; } // Set up which button options will be available for Administrator else if (LogonForm.personType == "Administrator") { btnCourses.Enabled = true; btnQualifications.Enabled = true; btnMarks.Enabled = false; btnTeachers.Enabled = true;

Page 4: School System C# Code

btnStudents.Enabled = true; btnAdministrators.Enabled = true; btnChangePassword.Enabled = true; } }

private void btnLogoff_Click(object sender, EventArgs e) { // Return to the logon screen this.Close(); }

private void btnMarks_Click(object sender, EventArgs e) { this.Hide(); //Hide the main menu MarksForm marks = new MarksForm(); marks.ShowDialog(); this.Show(); // show main menu when user exits marks }

private void btnQualifications_Click(object sender, EventArgs e) { this.Hide(); //Hide the main menu QualificationsForm qualifications = new QualificationsForm(); qualifications.ShowDialog(); this.Show(); // show main menu when user exits qualifications }

private void btnCourses_Click(object sender, EventArgs e) { this.Hide(); //Hide the main menu CoursesForm courses = new CoursesForm(); courses.ShowDialog(); this.Show(); // show main menu when user exits courses }

private void btnAdministrators_Click(object sender, EventArgs e) { // The StudentsForm is used for maintaining // Student, Teacher and Administrator data this.Hide(); //Hide the main menu

MenuChoice = "Administrator"; StudentsForm students = new StudentsForm(); students.ShowDialog(); this.Show(); // show main menu when user exits administrators }

private void btnTeachers_Click(object sender, EventArgs e) { // The StudentsForm is used for maintaining // Student, Teacher and Administrator data this.Hide(); //Hide the main menu

MenuChoice = "Teacher"; StudentsForm students = new StudentsForm(); students.ShowDialog(); this.Show(); // show main menu when user exits teachers }

private void btnStudents_Click(object sender, EventArgs e) { // The StudentsForm is used for maintaining // Student, Teacher and Administrator data this.Hide(); //Hide the main menu

Page 5: School System C# Code

MenuChoice = "Student"; StudentsForm students = new StudentsForm(); students.ShowDialog(); this.Show(); // show main menu when user exits students }

private void btnChangePassword_Click(object sender, EventArgs e) { this.Hide(); //Hide the main menu ChangePasswordForm password = new ChangePasswordForm(); password.ShowDialog(); this.Show(); // show main menu when user exits passwords } } }

Page 6: School System C# Code

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.Linq;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace SchoolSystem{ //Written by : Paul Smyth //Date of last issue : 9/9/2015 // // This form displays the required data entry mechanisms for the user // to add, edit and delete Courses records. // It reads and writes to the following tables with SQL TO LINQ procedures // Course // // public partial class CoursesForm : Form { SchoolDataClassesDataContext DB = new SchoolDataClassesDataContext();

// This bool is used to switch off a section of code that updates the // course ID combo box in the updateData method. This item does not need // to be refreshed after an update procedure because no course record // has been added or deleted. The benefit of this is that the updated // record in the Update Tab can still be displayed after the update // process has been completed instead of the first record in the // courses table. bool updated = false;

public CoursesForm() { InitializeComponent(); }

private void CoursesForm_Load(object sender, EventArgs e) { updateData(updated);

// Set up the initial help messages lblCoursesMessageA.Text = "Enter the new Course details and press the Add Button"; lblCoursesMessageU.Text = "Select a Course to edit from the Course ID drop down box";

// Setup the ToolTips for this form toolTip1.SetToolTip(btnAddA, "Add the Course Record you have entered"); toolTip1.SetToolTip(btnDeleteU, "Delete the selected record from Courses"); toolTip1.SetToolTip(btnExitA, "Return to Main Menu"); toolTip1.SetToolTip(btnExitU, "Return to Main Menu"); toolTip1.SetToolTip(btnUpdateU, "Write the updated record to Courses"); toolTip1.SetToolTip(cmbCourseIDU, "Select the Course ID to edit/delete from the drop down list"); toolTip1.SetToolTip(cmbQualificationCodeA, "Select a Qualification Code from the drop down list"); toolTip1.SetToolTip(cmbSemesterA, "Select a Semester from the drop down list"); toolTip1.SetToolTip(cmbSemesterU, "Select a Semester from the drop down list"); toolTip1.SetToolTip(cmbTeacherIDA, "Select a Teacher from the drop down list"); toolTip1.SetToolTip(cmbTeacherIDU, "Select a Teacher from the drop down list"); toolTip1.SetToolTip(cmbYearA, "Select a Year from the drop down list"); toolTip1.SetToolTip(cmbYearU, "Select a Year from the drop down list");

Page 7: School System C# Code

toolTip1.SetToolTip(txtCourseIDA, "Enter a unique Course ID"); toolTip1.SetToolTip(txtCourseNameA, "Enter the Course Name"); toolTip1.SetToolTip(txtCourseNameU, "Edit the Course Name"); }

// This method performs the required updates for all tables and combo // boxes used by this form. It makes sure the correct data is displayed // for the chosen ID private void updateData(bool fromUpdate) { // Update the Course data var courseList = (from c in DB.Courses select c).ToList();

// Update the Course ID Combo Box // as long as this method wasn't called by the // update button event method. if (fromUpdate == false) { cmbCourseIDU.DisplayMember = "CID"; cmbCourseIDU.ValueMember = "CID"; cmbCourseIDU.DataSource = courseList; }

// Update the Teacher ID Combo Box display var teachercodes = (from t in DB.Teachers select t.TID).ToList();

cmbTeacherIDA.DisplayMember = "TID"; cmbTeacherIDA.ValueMember = "TID"; cmbTeacherIDA.DataSource = teachercodes;

// Update the Qualification Code Combo Box display var qualificationcodes = (from q in DB.Qualifications select q.QCode).ToList();

cmbQualificationCodeA.DisplayMember = "QCode"; cmbQualificationCodeA.ValueMember = "QCode"; cmbQualificationCodeA.DataSource = qualificationcodes;

// Reset all the Course text Fields in the Add Tab txtCourseIDA.Clear(); txtCourseNameA.Clear(); }

// This method performs the selection process for the courses // data when either the update screen is updated or the // value in the courses id combo box has changed. // It is called by the cmbCourseIDU_SelectedIndexChanged // and btnUpdateU_Click event internal void selectTheRecord() { String selectedYear; //store for the selected Year branch string selectedSemester; //store for the selcted Semester branch

// Select the Course Record with the Course ID selected // from the Course ID Combo Box. var course = (from c in DB.Courses where c.CID == Convert.ToInt32(cmbCourseIDU.Text) select new { c.CName, c.Year,

Page 8: School System C# Code

c.Semester, c.TID } ).First();

txtCourseNameU.Text = course.CName; // Put the right year in the Combo Box. Either year 1 // year 2 or year 3. selectedYear = course.Year.ToString(); switch (selectedYear) { case "1": cmbYearU.SelectedIndex = 0; break; case "2": cmbYearU.SelectedIndex = 1; break; case "3": cmbYearU.SelectedIndex = 2; break; }

// Put the right Semester in the Combo Box selectedSemester = course.Semester; switch (selectedSemester) { case "Autumn": cmbSemesterU.SelectedIndex = 0; break; case "Winter": cmbSemesterU.SelectedIndex = 1; break; case "Spring": cmbSemesterU.SelectedIndex = 2; break; } // Update the Teacher ID Combo Box display var teachercodes = (from t in DB.Teachers select t.TID).ToList();

cmbTeacherIDU.DisplayMember = "TID"; cmbTeacherIDU.ValueMember = "TID"; cmbTeacherIDU.DataSource = teachercodes;

//Put the correct teacher Code in the Combo Box int codeCount = 0; int theCode = 0; foreach (int code in teachercodes) { if (code == course.TID) { theCode = codeCount; } codeCount++; } cmbTeacherIDU.SelectedIndex = theCode;

// Lookup the selected teachers name and put it in the label // adjacent to the Teacher ID combo on the form

var teacherName = (from t in DB.Persons where t.ID == int.Parse(cmbTeacherIDU.SelectedItem.ToString()) select new

Page 9: School System C# Code

{ t.FName, t.LName }).First();

lblTeacherNameU.Text = teacherName.FName + " " + teacherName.LName;

} // This method fills in the Update screen data properties based on // the criteria set by the Course ID Combo box selection private void cmbCourseIDU_SelectedIndexChanged(object sender, EventArgs e) { selectTheRecord(); }

// This section contains a series of methods that tests the data entry // fields for both the Add and Update Tabs. Each method tests what is the // current screen is and creates an error message if required. They are // activated by the Add and Update Button events.

// This method tests the course number to check // that it is valid. // Only required for Add private bool ValidCourseID(string courseID) { if (courseID == "") { lblCourseIDMessageA.Text = "Please enter a valid numeric course number"; return false; } else if (int.Parse(courseID) >= 0 & int.Parse(courseID) <= 99999) { lblCourseIDMessageA.Text = ""; return true; } else { lblCourseIDMessageA.Text = "Please enter a valid numeric course number"; return false; } }

// This method tests the course number to check that it is // not a duplicate. Only required for Add private bool validUniqueCourseNumber(string courseID) { // Lookup the existing course numbers var coursenumbers = (from c in DB.Courses select c.CID).ToList();

foreach (int course in coursenumbers) { if (course == int.Parse(courseID)) { lblCourseIDMessageA.Text = "This course number has already been used"; return false; } }

Page 10: School System C# Code

lblCourseIDMessageA.Text = ""; return true; }

// This method tests the course name to make sure that it is not blank private bool ValidCourseName(string coursename, string tab) { if (coursename != "") { if (tab == "Add") { lblCourseNameMessageA.Text = ""; } else if (tab == "Update") { lblCourseNameMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblCourseNameMessageA.Text = "Please enter a course name"; } else if (tab == "Update") { lblCourseNameMessageU.Text = "Please enter a course name"; } return false; } }

// This method tests the year to make sure that it is not blank // Only required for Add private bool ValidYear(string year) { if (year != "") { lblYearMessageA.Text = ""; return true; } else { lblYearMessageA.Text = "Please select a year"; return false; } }

// This method tests the semester to make sure that it is not blank // Only required for Add private bool ValidSemester(string semester) { if (semester != "") { lblSemesterMessageA.Text = ""; return true; } else { lblSemesterMessageA.Text = "Please select a semester"; return false; } }

Page 11: School System C# Code

// This method updates the Course table private void btnUpdateU_Click(object sender, EventArgs e) { try { // Indicate that this is the Update Tab for Error Message control string theTab = "Update";

// Test that a course name has been entered if (!ValidCourseName(txtCourseNameU.Text, theTab)) { return; }

// Update the Course record in the Courses Table var courseList = (from c in DB.Courses where c.CID == Convert.ToInt32(cmbCourseIDU.Text) select c).First();

courseList.CName = txtCourseNameU.Text.Trim(); courseList.Year = (int)int.Parse(cmbYearU.SelectedItem.ToString()); courseList.Semester = cmbSemesterU.SelectedItem.ToString(); courseList.TID = (int)cmbTeacherIDU.SelectedItem;

// Save the changes that were made DB.SubmitChanges();

// Refresh the Bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Courses);

lblCoursesMessageU.Text = "Course ID " + cmbCourseIDU.Text + " has been updated";

updated = true; updateData(updated); selectTheRecord(); updated = false; }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

// This method adds data to the Courses table private void btnAddA_Click(object sender, EventArgs e) { try { // Indicate that this is the Add Tab for Error Message control string theTab = "Add";

// Test that a valid course number has been entered if (!ValidCourseID(txtCourseIDA.Text)) { return; }

// Test that a unique Course number has been entered if (!validUniqueCourseNumber(txtCourseIDA.Text)) { return; }

Page 12: School System C# Code

// Test that a course name has been entered if (!ValidCourseName(txtCourseNameA.Text, theTab)) { return; }

// Test that a year has been selected if (!ValidYear(cmbYearA.Text)) { return; }

// Test that a semester has been selected if (!ValidSemester(cmbSemesterA.Text)) { return; }

// Create a new Courses object and add its properties var newCourse = new Course(); newCourse.CID = int.Parse(txtCourseIDA.Text.ToString()); newCourse.CName = txtCourseNameA.Text.Trim(); newCourse.Year = int.Parse(cmbYearA.SelectedItem.ToString()); newCourse.Semester = cmbSemesterA.SelectedItem.ToString(); newCourse.TID = int.Parse(cmbTeacherIDA.SelectedItem.ToString());

// Add the new course to the database DB.Courses.InsertOnSubmit(newCourse); DB.SubmitChanges();

// Create a new Qualification_Courses object and // add its properties var newQualCourse = new Qualification_Course(); newQualCourse.QCode = cmbQualificationCodeA.SelectedItem.ToString(); newQualCourse.CID = int.Parse(txtCourseIDA.Text.ToString());

// Add the new record to the database DB.Qualification_Courses.InsertOnSubmit(newQualCourse); DB.SubmitChanges();

lblCoursesMessageA.Text = "Course ID " + txtCourseIDA.Text + " added";

updateData(updated); }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

// This method deletes the selected rcord in the update screen // from the Courses table. private void btnDeleteU_Click(object sender, EventArgs e) { try { // Get the course that matches the criteria in the course ID // combo box var deletedCourse = (from c in DB.Courses where c.CID == (int)cmbCourseIDU.SelectedValue select c).First();

Page 13: School System C# Code

DialogResult d = MessageBox.Show("Are you sure you want to delete this Course?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (d == DialogResult.Yes) { DB.Courses.DeleteOnSubmit(deletedCourse); DB.SubmitChanges();

updateData(updated);

MessageBox.Show("Course deleted"); }

else if (d == DialogResult.No) { MessageBox.Show("Delete operation cancelled"); } }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

//Lookup the selected teachers name and put it in the adjacent label //in the Update form private void cmbTeacherIDU_SelectedIndexChanged(object sender, EventArgs e) { var teacherName = (from t in DB.Persons where t.ID == int.Parse(cmbTeacherIDU.SelectedItem.ToString()) select new { t.FName, t.LName }).First();

lblTeacherNameU.Text = teacherName.FName + " " + teacherName.LName; }

// Lookup the selected teachers name and put it in the adjacent label // in the Add form private void cmbTeacherIDA_SelectedIndexChanged(object sender, EventArgs e) { var teacherName = (from t in DB.Persons where t.ID == int.Parse(cmbTeacherIDA.SelectedItem.ToString()) select new { t.FName, t.LName }).First();

lblTeacherNameA.Text = teacherName.FName + " " + teacherName.LName; }

// Lookup the selected qualification name and put it in the adjacent // label in the Add form private void cmbQualificationCodeA_SelectedIndexChanged(object sender, EventArgs e) { var qualificationName = (from q in DB.Qualifications where q.QCode == cmbQualificationCodeA.Text select q.QName).First();

Page 14: School System C# Code

lblQualificationNameA.Text = qualificationName; }

// This method exits from the Add screen private void btnExitA_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

// This method exits from the Update screen private void btnExitU_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; } }}

Page 15: School System C# Code

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.Linq;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace SchoolSystem{ public partial class MarksForm : Form { SchoolDataClassesDataContext DB = new SchoolDataClassesDataContext();

public MarksForm() { InitializeComponent(); }

// This is what happens when the form is first loaded private void MarksForm_Load(object sender, EventArgs e) { var studentList = (from s in DB.Persons where s.Type == "Student" select new { s.ID, s.FName, s.LName } ).ToList(); cmbStudentIDS.DisplayMember = "ID"; cmbStudentIDS.ValueMember = "ID"; cmbStudentIDS.DataSource = studentList;

var courseList = (from c in DB.Courses select new { c.CID, c.CName } ).ToList();

cmbCourseIDC.DisplayMember = "CID"; cmbCourseIDC.ValueMember = "CID"; cmbCourseIDC.DataSource = courseList;

// Switch off the add student course panel // It will be switched on when the user clicks the // Add Course button in the view by students tab. pnlAddStudentS.Visible = false;

// Put the default tab header in place tabStudent.Text = "View Marks by Student";

// Set up the ToolTips for this form toolTip1.SetToolTip(btnAddStudentS, "Click here to go to the Add Record Screen"); toolTip1.SetToolTip(btnDeleteS, "Click here to delete the selected record in the Grid"); toolTip1.SetToolTip(btnExitC, "Click here to return to the Main Menu"); toolTip1.SetToolTip(btnExitS, "Click here to return to the Main Menu"); toolTip1.SetToolTip(btnPanelAddStudentS, "Click here to save the Record"); toolTip1.SetToolTip(btnPanelCancelS, "Click here to cancel the edit. The Record will not be added"); toolTip1.SetToolTip(btnPanelUpdateStudentS, "Click here to update the Record"); toolTip1.SetToolTip(btnUpdateS, "Click here to go to the Update Screen for the selected record in the Grid"); toolTip1.SetToolTip(cmbPanelCourseIDS, "Select a Course ID from the drop down list"); toolTip1.SetToolTip(cmbCourseIDC, "Select a Course ID from the drop down list"); toolTip1.SetToolTip(cmbStudentIDS, "Select a Student ID from the drop down list");

Page 16: School System C# Code

toolTip1.SetToolTip(txtPanelMarkS, "Enter a mark between 0 and 100 (decimal values are not permitted)");

lblMarksByStudentsMessage.Text = "Click on a record to select it to update or delete it"; }

// This method fills in the Marks by Course screen data properties based on // the criteria set by the Course ID Combo box selection private void cmbCourseIDC_SelectedIndexChanged(object sender, EventArgs e) { selectTheCourse(); }

// This method runs the script called by cmbCourseIDC_SelectedIndexChanged // event. It is seperated because it is also called by the // btnPanelAddStudentS_Click to make sure that the latest course // information is displayed in the courses dgv after a student // course record has been added. internal void selectTheCourse() { // Reset the datagrid before performing the query // because this method seems to append new columns // to the datagrid when it is run. dgvMarksC.DataSource = null; dgvMarksC.Columns.Clear(); dgvMarksC.Rows.Clear();

// Select the Courses Marks with the Course ID // selected in the Course ID Combo Box var marksByCourseList = (from c in DB.Student_Courses join p in DB.Persons on c.SID equals p.ID where c.CID == Convert.ToInt32(cmbCourseIDC.Text) select new { c.SID, p.FName, p.LName, c.Mark } ).ToList();

dgvMarksC.DataSource = marksByCourseList;

// Setup the by course datagrid dgvMarksC.Columns[0].HeaderText = "ID"; dgvMarksC.Columns[0].Width = 60; dgvMarksC.Columns[0].ReadOnly = true; dgvMarksC.Columns[1].HeaderText = "First Name"; dgvMarksC.Columns[1].Width = 120; dgvMarksC.Columns[1].ReadOnly = true; dgvMarksC.Columns[2].HeaderText = "Last Name"; dgvMarksC.Columns[2].Width = 120; dgvMarksC.Columns[2].ReadOnly = true; dgvMarksC.Columns[3].HeaderText = "Mark"; dgvMarksC.Columns[3].Width = 40;

// Get the Course name for the selected Course ID // displayed in the Combo Box var courseName = (from n in DB.Courses where n.CID == Convert.ToInt32(cmbCourseIDC.Text) select n.CName).First();

lblCourseNameC.Text = courseName; }

// This method deletes a record from the student view datagrid private void btnDeleteS_Click(object sender, EventArgs e)

Page 17: School System C# Code

{ try { // Make the selected row go a different colour. dgvMarksS.CurrentRow.DefaultCellStyle.BackColor = Color.Red;

DialogResult d = MessageBox.Show("Are you sure you want to delete this record?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (d == DialogResult.Yes) { // Pick the criteria from the chosen row in the datagrid int rowSelected = dgvMarksS.CurrentCell.RowIndex; int deleteStudentID = Convert.ToInt32(cmbStudentIDS.Text); int deleteCourseID = int.Parse(dgvMarksS.Rows[rowSelected].Cells[0].Value.ToString());

// Get the record that matches the criteria var deleteStudentCourse = (from s in DB.Student_Courses where s.SID == deleteStudentID && s.CID == deleteCourseID select s).First();

DB.Student_Courses.DeleteOnSubmit(deleteStudentCourse); DB.SubmitChanges();

lblMarksByStudentsMessage.Text = "Course Record deleted"; dgvMarksS.CurrentRow.DefaultCellStyle.BackColor = Color.White;

// This method call makes sure that the course // tab details have been updated. selectTheCourse(); // Update the Marks by student screen updateMarksByStudent(); } else if (d == DialogResult.No) { lblMarksByStudentsMessage.Text = "Delete operation cancelled"; dgvMarksS.CurrentRow.DefaultCellStyle.BackColor = Color.White; return; } else { throw new NotSupportedException(); } } catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

// This method fills in the Marks by Student screen data properties based on // the criteria set by the Student ID Combo box selection private void cmbStudentIDS_SelectedIndexChanged(object sender, EventArgs e) { updateMarksByStudent(); }

internal void updateMarksByStudent() { // Change the Tab header

Page 18: School System C# Code

tabStudent.Text = "View Marks by Student";

// Reset the data grid before running the query // because this method seems to append new columns // to the datagrid when it is run. dgvMarksS.DataSource = null; dgvMarksS.Columns.Clear(); dgvMarksS.Rows.Clear();

// Select the Courses Marks with the student ID // selected i n the Course ID Combo Box var marksByStudentList = (from s in DB.Student_Courses join c in DB.Courses on s.CID equals c.CID where s.SID == Convert.ToInt32(cmbStudentIDS.Text) select new { s.CID, c.CName, s.Mark } ).ToList();

dgvMarksS.DataSource = marksByStudentList;

// Set up the by students Datagrid dgvMarksS.Columns[0].HeaderText = "ID"; dgvMarksS.Columns[0].Width = 60; dgvMarksS.Columns[0].ReadOnly = true; dgvMarksS.Columns[1].HeaderText = "Course Name"; dgvMarksS.Columns[1].Width = 120; dgvMarksS.Columns[1].ReadOnly = true; dgvMarksS.Columns[2].HeaderText = "Mark"; dgvMarksS.Columns[2].Width = 40;

// Get the Student name for the selected Student ID // displayed in the Combo Box var studentName = (from n in DB.Persons where n.ID == Convert.ToInt32(cmbStudentIDS.Text) select new { n.FName, n.LName } ).First();

lblStudentNameS.Text = studentName.FName + " " + studentName.LName; } // This method presents the Add Student Course panel and fills // the required data ready for data entry. private void btnAddStudentS_Click(object sender, EventArgs e) { string editing = "Add"; tabStudent.Text = "Add a Student Course / Mark"; //Change the Tab Header displayTheEditPanel(editing); }

private void btnUpdateS_Click(object sender, EventArgs e) { string editing = "Update"; tabStudent.Text = "Update a Student Mark"; displayTheEditPanel(editing); }

internal void displayTheEditPanel(string edited) { pnlAddStudentS.Visible = true; pnlCourseIDOverlayS.Visible = false; pnlUpdateRecordBtnS.Visible = false;

if (edited == "Add") {

Page 19: School System C# Code

txtPanelMarkS.Text = "0"; // default value displayed

// Update the Course ID Combo Box var courseList = (from c in DB.Courses select c.CID).ToList();

cmbPanelCourseIDS.DisplayMember = "CID"; cmbPanelCourseIDS.ValueMember = "CID"; cmbPanelCourseIDS.DataSource = courseList; } else if (edited == "Update") { // Cover up the Course ID Combo box with a Course ID label. // The combo box is not required in Update. pnlCourseIDOverlayS.Visible = true; pnlUpdateRecordBtnS.Visible = true; int rowSelected = dgvMarksS.CurrentCell.RowIndex; txtPanelOverlayCourseIDS.Text = dgvMarksS.Rows[rowSelected].Cells[0].Value.ToString(); txtPanelMarkS.Text = dgvMarksS.Rows[rowSelected].Cells[2].Value.ToString();

// Get the Course Name for the panel var courseName = (from n in DB.Courses where n.CID == int.Parse(txtPanelOverlayCourseIDS.Text) select n.CName).First();

lblPanelCourseNameS.Text = courseName; } txtPanelStudentIDS.Text = cmbStudentIDS.Text; lblPanelStudentNameS.Text = lblStudentNameS.Text; } // This method selects the course name in the Add Student Course panel // when the Course ID combo box value changes private void cmbPanelCourseIDS_SelectedIndexChanged(object sender, EventArgs e) { //Get the Course Name var courseName = (from n in DB.Courses where n.CID == int.Parse(cmbPanelCourseIDS.SelectedItem.ToString()) select n.CName).First();

lblPanelCourseNameS.Text = courseName; }

// This method updates the Student Course table with the data // that was entered on the add student course panel. It also // puts the Student ID that was selected for editing back into // the Student ID combo box. private void btnPanelAddStudentS_Click(object sender, EventArgs e) { string editing = "Add"; addOrUpdateMark(editing); }

private void btnPanelUpdateStudentS_Click(object sender, EventArgs e) { string editing = "Update"; addOrUpdateMark(editing); }

// This method is the guts of the Add / Update procedure called

Page 20: School System C# Code

// by btnPanelAddStudentS_Click or btnPanelUpdateStudentS_Click // button event. internal void addOrUpdateMark(string edited) { try { // Test the Mark value to see if it is a numeric // and not a string or decimal if (!validMarkIsNumber(txtPanelMarkS.Text)) { return; }

// Test the Mark value to see if it is between 0 and 99 if (!validMarkInRange(txtPanelMarkS.Text)) { return; }

if (edited == "Add") { // Test that the course ID has not already been selected for this student if (!validUniqueCourseNumber(cmbPanelCourseIDS.SelectedItem.ToString())) { return; }

// Write to the student courses table. var newStudentCourse = new Student_Course(); newStudentCourse.SID = int.Parse(txtPanelStudentIDS.Text); newStudentCourse.CID = int.Parse(cmbPanelCourseIDS.SelectedItem.ToString()); newStudentCourse.Mark = int.Parse(txtPanelMarkS.Text);

// DB.Student_Courses.InsertOnSubmit(newStudentCourse); DB.SubmitChanges(); } else if (edited == "Update") { var updateStudentCourse = (from u in DB.Student_Courses where u.SID == int.Parse(txtPanelStudentIDS.Text) && u.CID == int.Parse(txtPanelOverlayCourseIDS.Text) select u).First();

updateStudentCourse.Mark = int.Parse(txtPanelMarkS.Text);

// Save the changes that were made DB.SubmitChanges();

// Refresh the bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Student_Courses); }

//Put the existing Student ID back in the Student Combo Box var studentListPanel = (from s in DB.Persons where s.Type == "Student" select s.ID).ToList();

cmbStudentIDS.DisplayMember = "ID"; cmbStudentIDS.ValueMember = "ID"; cmbStudentIDS.DataSource = studentListPanel;

Page 21: School System C# Code

int codeCount = 0; int theCode = 0; foreach (int id in studentListPanel) { if (id == int.Parse(txtPanelStudentIDS.Text)) { theCode = codeCount; } codeCount++; } cmbStudentIDS.SelectedIndex = theCode;

// This method call makes sure that the course // tab details have been updated. selectTheCourse();

// Switch off the Add Student Course panel pnlAddStudentS.Visible = false;

if (edited == "Add") { lblMarksByStudentsMessage.Text = "Student Course details added"; } else if (edited == "Update") { lblMarksByStudentsMessage.Text = "Student Course mark updated"; } tabStudent.Text = "View Marks by Student"; //Change the Tab Header }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } } // This method checks to see if the mark is an actual integer private bool validMarkIsNumber(string markToCheck) { int number; bool result = Int32.TryParse(markToCheck, out number);

if (result) { lblPanelMarkMessageS.Text = ""; return true; } else { lblPanelMarkMessageS.Text = "Enter a whole number between 0 and 100"; return false; }

}

// This method checks to see if the mark number is between 0 and 100 private bool validMarkInRange(string markToCheck) { if (int.Parse(markToCheck) >= 0 && int.Parse(markToCheck) <= 100) { lblPanelMarkMessageS.Text = ""; return true; } else { lblPanelMarkMessageS.Text = "Enter a whole number between 0 and 100";

Page 22: School System C# Code

return false; } }

// This method checks to see if the course number hasn't already // been seleceted for the selected student. private bool validUniqueCourseNumber(string courseID) { // Get the list of courses for the student var coursenumbers = (from c in DB.Student_Courses where c.SID == Convert.ToInt32(txtPanelStudentIDS.Text) select c.CID).ToList();

// See if the selected course is on the list. foreach (int course in coursenumbers) { if (course == int.Parse(courseID)) { //lblPanelCourseNameS.ForeColor = 192, 0, 0; ?? lblPanelCourseNameS.Text = "This course number is already used by the student"; return false; } } return true; }

private void btnPanelCancelS_Click(object sender, EventArgs e) { pnlAddStudentS.Visible = false; tabStudent.Text = "View Marks by Student"; //Change the Tab Header lblMarksByStudentsMessage.Text = "Add/Edit function cancelled"; }

// This method exits the Marks by Student Screen private void btnExitS_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

// This method exits the Marks by Course Screen private void btnExitC_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

}

}

Page 23: School System C# Code

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.Linq;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace SchoolSystem{ //Written by : Paul Smyth //Date of last issue : 9/9/2015 // // This form displays the required data entry mechanisms for the user // to add, edit and delete Qualification records. // It reads and writes to the following tables with SQL TO LINQ procedures // Qualification // Qualification_Courses // // There is an extra tab on this form which displays 2 datagrids. // This tab screen is used to add or delete courses to qualifications. // The user clicks the record to add or delete and then clicks the // Add or Delete button to perform that action. A panel with basic // instructions can be called up by clicking a Help button on that tab.

public partial class QualificationsForm : Form { SchoolDataClassesDataContext DB = new SchoolDataClassesDataContext();

// This bool is used to switch off a section of code that updates the // qualification ID combo box in the updateData method. This item does not need // to be refreshed after an update procedure because no course record // has been added or deleted. The benefit of this is that the updated // record in the Update Tab can still be displayed after the update // process has been completed instead of the first record in the // courses table. bool updated = false;

public QualificationsForm() { InitializeComponent(); }

private void QualificationsForm_Load(object sender, EventArgs e) { updateData(updated);

pnlHelpC.Visible = false; // Make sure the Help panel is closed.

// Load Course data into the available courses dataset view // in the Add Delete Courses Tab

var courseList = (from c in DB.Courses select new { c.CID, c.CName } ).ToList();

dgvAvailableCoursesC.DataSource = courseList; dgvAvailableCoursesC.Columns[0].HeaderText = "ID"; dgvAvailableCoursesC.Columns[0].Width = 40; dgvAvailableCoursesC.Columns[1].HeaderText = "Name"; dgvAvailableCoursesC.Columns[1].Width = 152;

Page 24: School System C# Code

// Setup the ToolTips for this form toolTip1.SetToolTip(btnAddA, "Add the Qualification Record you have entered"); toolTip1.SetToolTip(btnAddC, "Add the Course you have selected in Available Courses Table"); toolTip1.SetToolTip(btnDeleteC, "Delete the Course you have selected in Courses Table"); toolTip1.SetToolTip(btnDeleteU, "Delete the selected record from Qualifications"); toolTip1.SetToolTip(btnExitA, "Return to Main Menu"); toolTip1.SetToolTip(btnExitC, "Return to Main Menu"); toolTip1.SetToolTip(btnExitU, "Return to Main Menu"); toolTip1.SetToolTip(btnUpdateU, "Write the updated record to Qualifications"); toolTip1.SetToolTip(cmbDurationA, "Select the duration period for this qualification from the drop down list"); toolTip1.SetToolTip(cmbQualificationIDC, "Select the Qualification you wish to inspect from the drop down list"); toolTip1.SetToolTip(cmbQualificationIDU, "Select the Qualification you wish to update/delete from the drop down list"); toolTip1.SetToolTip(txtQualificationIDA, "Enter a unique Qualification ID"); toolTip1.SetToolTip(txtQualificationNameA, "Enter the Qualification Name"); toolTip1.SetToolTip(txtQualificationNameU, "Change the Qualification Name"); }

//This method performs the required updates for all tables and combo //boxes used by this form. private void updateData(bool fromUpdate) { // Update the Qualification data var qualList = (from q in DB.Qualifications select q).ToList();

// Update the Qualification ID Combo Box // as long as this method wasn't called by the // update button event method. if (fromUpdate == false) { cmbQualificationIDU.DisplayMember = "QCode"; cmbQualificationIDU.ValueMember = "QCode"; cmbQualificationIDU.DataSource = qualList; }

// Update the Qualification/Course data var qualCourseList = (from c in DB.Qualification_Courses select c).ToList();

//Update the Qualification/Course ID Combo Box cmbQualificationIDC.DisplayMember = "QCode"; cmbQualificationIDC.ValueMember = "QCode"; cmbQualificationIDC.DataSource = qualList;

// Clear the Text fields on the Add Tab txtQualificationIDA.Clear(); txtQualificationNameA.Clear(); }

// This method fills in the Update screen data properties based on // the criteria set by the Qualification ID Combo box selection by using // the selectTheRecord method. selectTheRecord method is also called by the // btnUpdateU_Click event private void cmbQualificationIDU_SelectedIndexChanged(object sender, EventArgs e) { selectTheRecord();

Page 25: School System C# Code

}

// This method ensures that the correct data is displayed after an update // has been performed or the user has selected a different Qualification ID // in the update screen. It is called by the cmbQualificationIDU_SelectedIndexChanged // and btnUpdateU_Click event

internal void selectTheRecord() { string selectedDuration; // Store for the selected Duration branch

// Select the Qualification record with the Qualification ID // selected from the Qualification ID Combo Box

var qualification = (from q in DB.Qualifications where q.QCode == cmbQualificationIDU.Text select q).First();

txtQualificationNameU.Text = qualification.QName;

// Put the right duration in the Combo Box selectedDuration = qualification.Duration.ToString();

switch (selectedDuration) { case "1 month": cmbDurationU.SelectedIndex = 0; break; case "2 months": cmbDurationU.SelectedIndex = 1; break; case "3 months": cmbDurationU.SelectedIndex = 2; break; case "4 months": cmbDurationU.SelectedIndex = 3; break; case "5 months": cmbDurationU.SelectedIndex = 4; break; case "6 months": cmbDurationU.SelectedIndex = 5; break; case "7 months": cmbDurationU.SelectedIndex = 6; break; case "8 months": cmbDurationU.SelectedIndex = 7; break; case "9 months": cmbDurationU.SelectedIndex = 8; break; case "10 months": cmbDurationU.SelectedIndex = 9; break; case "11 months": cmbDurationU.SelectedIndex = 10; break; case "12 months": cmbDurationU.SelectedIndex = 11; break; } } // This section contains a series of methods that tests the data entry

Page 26: School System C# Code

// fields for both the Add and Update Tabs. Each method tests what is the // current screen is and creates an error message if required. They are // activated by the Add and Update Button events.

// This method tests the qualification ID // to make sure that it is not blank. // Only required for ADD private bool ValidQualificationID(string qualificationID) { if (qualificationID != "") { lblQualificationIDMessageA.Text = ""; return true; } else { lblQualificationIDMessageA.Text = "Please enter a valid qualification ID"; return false; } }

// This method tests the qualification name to make sure that it is not blank private bool ValidQualificationName(string qualificationname, string tab) { if (qualificationname != "") { if (tab == "Add") { lblQualificationNameMessageA.Text = ""; } else if (tab == "Update") { lblQualificationNameMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblQualificationNameMessageA.Text = "Please enter a qualification name"; } else if (tab == "Update") { lblQualificationNameMessageU.Text = "Please enter a qualification name"; } return false; } }

// This method tests the duration entry // to make sure that it is not blank. // Only required for ADD private bool ValidDuration(string duration) { if (duration != "") { lblDurationMessageA.Text = ""; return true; } else { lblDurationMessageA.Text = "Please enter a valid duration ID"; return false; }

Page 27: School System C# Code

}

// This method updates the Qualification table private void btnUpdateU_Click(object sender, EventArgs e) { try { // Indicate that this is the Update Tab for Error Message control string theTab = "Update";

// Test that the qualification name has been entered if (!ValidQualificationName(txtQualificationNameU.Text, theTab)) { return; }

// Update the selected record in the Qualifications table var qualification = (from q in DB.Qualifications where q.QCode == cmbQualificationIDU.Text select q).First();

qualification.QName = txtQualificationNameU.Text; qualification.Duration = cmbDurationU.SelectedItem.ToString();

// Save the changes that were made DB.SubmitChanges();

// Refresh the Bound Controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Qualifications);

MessageBox.Show("Qualification Code " + qualification.QCode + " updated");

updated = true; updateData(updated); selectTheRecord(); updated = false; }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

// This method verifies the data added in the Add screen // and then writes the data to the Qualifications table. private void btnAddA_Click(object sender, EventArgs e) { try { // Indicate that this is the Add Tab for Error Message control string theTab = "Add";

// Test that the qualification ID has been entered if (!ValidQualificationID(txtQualificationIDA.Text)) { return; }

// Test that the qualification name has been entered if (!ValidQualificationName(txtQualificationNameA.Text, theTab)) { return; }

Page 28: School System C# Code

// Test that the duration has been selected if (!ValidDuration(cmbDurationA.Text)) { return; }

// Create a new Qualifications object and add its properties var newQualification = new Qualification(); newQualification.QCode = txtQualificationIDA.Text.Trim(); newQualification.QName = txtQualificationNameA.Text.Trim(); newQualification.Duration = cmbDurationA.SelectedItem.ToString(); // Add the new Qualification to the database DB.Qualifications.InsertOnSubmit(newQualification); DB.SubmitChanges();

MessageBox.Show("Qualification " + newQualification.QCode + " added"); updateData(updated); }

catch(Exception Ex) { MessageBox.Show(Ex.Message); } }

// This method deletes the selected Qualification listed in // the Combo box from the Qualification Table. It also // deletes the associated Qualification_Course table records too. private void btnDeleteU_Click(object sender, EventArgs e) { try { var deletedQualification = (from q in DB.Qualifications where q.QCode == cmbQualificationIDU.Text select q).First();

var deletedQualificationCourse = (from c in DB.Qualification_Courses where c.QCode == cmbQualificationIDU.Text select c).ToList();

DialogResult d = MessageBox.Show("Are you sure you want to delete this Qualification?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (d == DialogResult.Yes) { DB.Qualifications.DeleteOnSubmit(deletedQualification); DB.Qualification_Courses.DeleteAllOnSubmit(deletedQualificationCourse); DB.SubmitChanges(); updateData(updated);

MessageBox.Show("Qualification deleted"); }

else if (d == DialogResult.No) { MessageBox.Show("Delete operation cancelled"); } }

catch (Exception Ex) {

Page 29: School System C# Code

MessageBox.Show(Ex.Message); } }

// This method selects The Qualification/Course data to display based // on what is selected in the Qualification ID Combo Box. It also // Looks up the Qualification name for the selected qualification. // The Available Courses datagrid is updated by the UpdateData method private void cmbQualificationIDC_SelectedIndexChanged(object sender, EventArgs e) { var qualCourseList = (from q in DB.Qualification_Courses join c in DB.Courses on q.CID equals c.CID where q.QCode == cmbQualificationIDC.Text select new { q.CID, c.CName } ).ToList();

dgvCoursesC.DataSource = qualCourseList; dgvCoursesC.Columns[0].HeaderText = "ID"; dgvCoursesC.Columns[0].Width =40; dgvCoursesC.Columns[1].HeaderText = "Name"; dgvCoursesC.Columns[1].Width = 152;

var qualName = (from n in DB.Qualifications where n.QCode == cmbQualificationIDC.Text select n.QName).First();

lblQualificationNameC.Text = qualName; }

// This method copies the selected record from the available courses datagrid // and copies it to the qualification courses table. Then it updates the // qualification courses datagrid. private void btnAddC_Click(object sender, EventArgs e) { try { // Store the current selected Combo value so that it // can be selected after the process is finished. var theQualificationID = cmbQualificationIDC.SelectedIndex;

//Select the selected Course ID from the Course datagrid int rowSelected = dgvAvailableCoursesC.CurrentCell.RowIndex; var selectedCourseIDNumber = dgvAvailableCoursesC.Rows[rowSelected].Cells[0].Value.ToString();

// Check that it is not already been added to the // selected Qualification var cidList = (from q in DB.Qualification_Courses where q.QCode == cmbQualificationIDC.Text select q.CID).ToList();

foreach (int c in cidList) { if (c == int.Parse(selectedCourseIDNumber)) { MessageBox.Show("The selected course has already been added"); return; } } // Use the selected Qualification Code and Course ID to // create a new Qualification_Course record var newQualificationCourse = new Qualification_Course();

Page 30: School System C# Code

newQualificationCourse.QCode = cmbQualificationIDC.SelectedValue.ToString(); newQualificationCourse.CID = int.Parse(selectedCourseIDNumber);

DB.Qualification_Courses.InsertOnSubmit(newQualificationCourse); DB.SubmitChanges();

MessageBox.Show("Course added to Qualification");

updateData(updated);

// Recall the selected combo value cmbQualificationIDC.SelectedIndex = theQualificationID; }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

// This method will delete the selected record in the // Qualification_Course datagrid private void btnDeleteC_Click(object sender, EventArgs e) { try { // Store the current selected Combo value so that it // can be selected after the process is finished. var theQualificationID = cmbQualificationIDC.SelectedIndex;

// Identify the Qualification_Course record to delete // from the datagrid. int rowSelected = dgvCoursesC.CurrentCell.RowIndex; var selectedCID = dgvCoursesC.Rows[rowSelected].Cells[0].Value;

var deletedQualificationCourse = (from c in DB.Qualification_Courses where c.QCode == cmbQualificationIDU.Text && c.CID == (int) selectedCID select c).First();

DialogResult d = MessageBox.Show("Are you sure you want to delete this Qualification?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (d == DialogResult.Yes) { DB.Qualification_Courses.DeleteOnSubmit(deletedQualificationCourse); DB.SubmitChanges();

updateData(updated);

// Recall the selected combo value cmbQualificationIDC.SelectedIndex = theQualificationID;

MessageBox.Show("Qualification Course deleted"); }

else if (d == DialogResult.No) { MessageBox.Show("Delete operation cancelled"); } }

catch (Exception Ex) {

Page 31: School System C# Code

MessageBox.Show(Ex.Message); } }

// This method exits from the Add screen private void btnExitA_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

// This method exits from the Update screen private void btnExitU_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

// This method exits from the Change Courses screen private void btnExitC_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

// Close the Help Panel private void btnCloseHelpC_Click(object sender, EventArgs e) { pnlHelpC.Visible = false; }

// Open the Help Panel private void btnHelpC_Click(object sender, EventArgs e) { pnlHelpC.Visible = true; } }

}

Page 32: School System C# Code

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.Linq;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace SchoolSystem{ //Written by : Paul Smyth //Date of last issue : 9/9/2015 // // This form displays the required data entry mechanisms for the user // to add, edit and delete student, teacher and administrator records. // It reads and writes to the following tables with SQL TO LINQ procedures // Person // Teacher // Student // Administration // // NOTE //Even though this form is called StudentsForm, it also includes //code to operate the requirements for the Teacher and //Administrator forms too. This version was neccessary to //reduce the code duplication that resulted from running //three very similar forms.

public partial class StudentsForm : Form { SchoolDataClassesDataContext DB = new SchoolDataClassesDataContext();

// This bool is used to switch off a section of code that updates the // Person ID combo box in the updateData method. This item does not need // to be refreshed after an update procedure because no course record // has been added or deleted. The benefit of this is that the updated // record in the Update Tab can still be displayed after the update // process has been completed instead of the first record in the // courses table. bool updated = false;

public StudentsForm() { InitializeComponent(); }

private void StudentsForm_Load(object sender, EventArgs e) { // Update the form header this.Text = MainMenuForm.MenuChoice + " Form";

// Set up the initial help messages lblAddMessage.Text = "Enter the new " + MainMenuForm.MenuChoice + " details and press the Add Button"; lblUpdateMessage.Text = "Select a " + MainMenuForm.MenuChoice + " ID to edit from the Course ID drop down box";

UpdateData(updated); // resets the fields and combo boxes

// Setup the form according to what menu option was selected.

Page 33: School System C# Code

// The fields relating to person will stay the same on the form // and extra fields will be added for the required student, // teacher or administrator option.

if (MainMenuForm.MenuChoice == "Student") { lblQNameA.Enabled = true; lblQNameU.Enabled = true; lblQualificationCodeA.Enabled = true; lblQualificationCodeU.Enabled = true; cmbQualificationCodeA.Enabled = true; cmbQualificationCodeU.Enabled = true; lblStartDateA.Enabled = true; lblStartDateU.Enabled = true; dtpStartDateA.Enabled = true; dtpStartDateU.Enabled = true; lblTeacherRegA.Enabled = false; lblTeacherRegU.Enabled = false; lblTeacherRegMessageA.Enabled = false; lblTeacherRegMessageU.Enabled = false; txtTeacherRegA.Enabled = false; txtTeacherRegU.Enabled = false; lblAdminRoleA.Enabled = false; lblAdminRoleU.Enabled = false; lblAdminRoleMessageA.Enabled = false; lblAdminRoleMessageU.Enabled = false; txtAdminRoleA.Enabled = false; txtAdminRoleU.Enabled = false;

} else if (MainMenuForm.MenuChoice == "Teacher") { lblQNameA.Enabled = false; lblQNameU.Enabled = false; lblQualificationCodeA.Enabled = false; lblQualificationCodeU.Enabled = false; cmbQualificationCodeA.Enabled = false; cmbQualificationCodeU.Enabled = false; lblStartDateA.Enabled = false; lblStartDateU.Enabled = false; dtpStartDateA.Enabled = false; dtpStartDateU.Enabled = false; lblTeacherRegA.Enabled = true; lblTeacherRegU.Enabled = true; lblTeacherRegMessageA.Enabled = true; lblTeacherRegMessageU.Enabled = true; txtTeacherRegA.Enabled = true; txtTeacherRegU.Enabled = true; lblAdminRoleA.Enabled = false; lblAdminRoleU.Enabled = false; lblAdminRoleMessageA.Enabled = false; lblAdminRoleMessageU.Enabled = false; txtAdminRoleA.Enabled = false; txtAdminRoleU.Enabled = false; } else if (MainMenuForm.MenuChoice == "Administrator") { lblQNameA.Enabled = false; lblQNameU.Enabled = false; lblQualificationCodeA.Enabled = false; lblQualificationCodeU.Enabled = false; cmbQualificationCodeA.Enabled = false; cmbQualificationCodeU.Enabled = false; lblStartDateA.Enabled = false; lblStartDateU.Enabled = false;

Page 34: School System C# Code

dtpStartDateA.Enabled = false; dtpStartDateU.Enabled = false; lblTeacherRegA.Enabled = false; lblTeacherRegU.Enabled = false; lblTeacherRegMessageA.Enabled = false; lblTeacherRegMessageU.Enabled = false; txtTeacherRegA.Enabled = false; txtTeacherRegU.Enabled = false; lblAdminRoleA.Enabled = true; lblAdminRoleU.Enabled = true; lblAdminRoleMessageA.Enabled = true; lblAdminRoleMessageU.Enabled = true; txtAdminRoleA.Enabled = true; txtAdminRoleU.Enabled = true; } else { throw new NotSupportedException(); }

// Setup thetooltips for ths form toolTip1.SetToolTip(btnAddA, "Add the " + MainMenuForm.MenuChoice + " Record you have entered"); toolTip1.SetToolTip(btnDeleteU, "Delete the selected record from " + MainMenuForm.MenuChoice + "s"); toolTip1.SetToolTip(btnExitA, "Return to Main Menu"); toolTip1.SetToolTip(btnExitU, "Return to Main Menu"); toolTip1.SetToolTip(btnUpdateU, "Update the " + MainMenuForm.MenuChoice + " Record you have entered"); toolTip1.SetToolTip(cmbPersonIDU, "Select the "+ MainMenuForm.MenuChoice + " ID to edit/delete from the drop down list"); toolTip1.SetToolTip(cmbQualificationCodeA, "Select a Qualification Code from the drop down list"); toolTip1.SetToolTip(cmbQualificationCodeU, "Select a Qualification Code from the drop down list"); toolTip1.SetToolTip(cmbStateA, "Select a State from the drop down list"); toolTip1.SetToolTip(cmbStateU, "Select a State from the drop down list"); toolTip1.SetToolTip(txtAddress1A, "Input the first line of the Address. This is required"); toolTip1.SetToolTip(txtAddress1U, "Input the first line of the Address. This is required"); toolTip1.SetToolTip(txtAddress2A, "Input the second line of the Address. This is optional"); toolTip1.SetToolTip(txtAddress2U, "Input the second line of the Address. This is optional"); toolTip1.SetToolTip(txtPhoneA, "Input a phone number. Either a mobile number or a land line number with the correct area code for the state. This is required"); toolTip1.SetToolTip(txtPhoneU, "Input a phone number. Either a mobile number or a land line number with the correct area code for the state. This is required"); toolTip1.SetToolTip(txtPostcodeA, "Input the Postcode. This is required"); toolTip1.SetToolTip(txtPostcodeU, "Input the Postcode. This is required"); toolTip1.SetToolTip(txtSuburbA, "Input the Suburb. This is required"); toolTip1.SetToolTip(txtSuburbU, "Input the Suburb. This is required"); toolTip1.SetToolTip(txtTeacherRegA, "Input the Teacher Registration. This is required"); toolTip1.SetToolTip(txtTeacherRegU, "Input the Teacher Registration. This is required"); toolTip1.SetToolTip(txtFirstNameA, "Input the First Name. This is required"); toolTip1.SetToolTip(txtFirstNameU, "Input the First Name. This is required"); toolTip1.SetToolTip(txtLastNameA, "Input the Last Name. This is required"); toolTip1.SetToolTip(txtLastNameU, "Input the Last Name. This is required"); toolTip1.SetToolTip(dtpDateOfBirthA, "Select the Date of Birth"); toolTip1.SetToolTip(dtpDateOfBirthU, "Select the Date of Birth"); toolTip1.SetToolTip(dtpStartDateA, "Select the Student's Start Date"); toolTip1.SetToolTip(dtpStartDateU, "Select the Student's Start Date");

Page 35: School System C# Code

}

// This method performs the required screen updates for all text and combo // boxes used by this form. It is called by the btnAddA_Click // and btnUpdateU_Click event private void UpdateData(bool fromUpdate) { if (MainMenuForm.MenuChoice == "Student") { // Select the Student record from the Person & Student database var personList = (from p in DB.Persons join s in DB.Students on p.ID equals s.SID select new { p.ID, p.FName, p.LName, p.DOB, p.Phone, p.Add1, p.Add2, p.Suburb, p.State, p.Postcode, s.Sdate, s.QCode } ).ToList();

// Update the Person ID combo box data // as long as this method wasn't called by the // update button event method. if (fromUpdate == false) { cmbPersonIDU.DisplayMember = "ID"; cmbPersonIDU.ValueMember = "ID"; cmbPersonIDU.DataSource = personList; }

// Update the Qualification Code Combo Box display var qualcodes = (from q in DB.Qualifications select q.QCode).ToList();

cmbQualificationCodeA.DisplayMember = "QCode"; cmbQualificationCodeA.ValueMember = "QCode"; cmbQualificationCodeA.DataSource = qualcodes;

// Reset the Student start date to todays date // on the Add Tab dtpStartDateA.Value = DateTime.Today; } else if (MainMenuForm.MenuChoice == "Teacher") { // Select the teacher record from the Person & Teacher database var teacherList = (from p in DB.Persons join t in DB.Teachers on p.ID equals t.TID select new { p.ID, p.FName, p.LName,

Page 36: School System C# Code

p.DOB, p.Phone, p.Add1, p.Add2, p.Suburb, p.State, p.Postcode, t.RegNo } ).ToList();

// Update the Student ID combo box data // as long as this method wasn't called by the // update button event method. if (fromUpdate == false) { cmbPersonIDU.DisplayMember = "ID"; cmbPersonIDU.ValueMember = "ID"; cmbPersonIDU.DataSource = teacherList; } txtTeacherRegA.Clear(); // reset the teacher registration text field on the Add Tab

} else if (MainMenuForm.MenuChoice == "Administrator") { // Select the Administrator record from the Person & Administrator database var adminList = (from p in DB.Persons join a in DB.Administrations on p.ID equals a.AID select new { p.ID, p.FName, p.LName, p.DOB, p.Phone, p.Add1, p.Add2, p.Suburb, p.State, p.Postcode, a.Role } ).ToList();

// Update the Student ID combo box data // as long as this method wasn't called by the // update button event method. if (fromUpdate == false) { cmbPersonIDU.DisplayMember = "ID"; cmbPersonIDU.ValueMember = "ID"; cmbPersonIDU.DataSource = adminList; } txtAdminRoleA.Clear(); // reset the Administrator registration text field on the Add Tab } else { throw new NotSupportedException(); }

// Reset all the Person Fields on the Add Tab txtFirstNameA.Clear();

Page 37: School System C# Code

txtLastNameA.Clear(); dtpDateOfBirthA.Value = DateTime.Today; // Reset the birthday to todays date txtPhoneA.Clear(); txtAddress1A.Clear(); txtAddress2A.Clear(); txtSuburbA.Clear(); txtPostcodeA.Clear(); }

// This method ensures that the correct data is displayed for the student, teacher // and administrator when either the update screen is updated or the // value in the student id combo box has changed. // It is called by the cmbStudentIDU_SelectedIndexChanged // and btnUpdateU_Click events internal void selectTheRecord() { string selectedState; // store for the selected state branch statement

// Select the Student record from the Person & Student database

var person = (from p in DB.Persons where p.ID == Convert.ToInt32(cmbPersonIDU.Text) select p).First();

txtFirstNameU.Text = person.FName; txtLastNameU.Text = person.LName; dtpDateOfBirthU.Value = person.DOB; txtPhoneU.Text = person.Phone; txtAddress1U.Text = person.Add1; txtAddress2U.Text = person.Add2; txtSuburbU.Text = person.Suburb;

// Put the right State in the State Combo Box selectedState = person.State; switch (selectedState) { case "NSW": cmbStateU.SelectedIndex = 0; break; case "VIC": cmbStateU.SelectedIndex = 1; break; case "QLD": cmbStateU.SelectedIndex = 2; break; case "SA": cmbStateU.SelectedIndex = 3; break; case "WA": cmbStateU.SelectedIndex = 4; break; case "ACT": cmbStateU.SelectedIndex = 5; break; case "NT": cmbStateU.SelectedIndex = 6; break; case "TAS": cmbStateU.SelectedIndex = 7; break; default: throw new NotSupportedException(); }

Page 38: School System C# Code

txtPostcodeU.Text = person.Postcode;

if (MainMenuForm.MenuChoice == "Student") { // Select the required data var student = (from s in DB.Students where s.SID == Convert.ToInt32(cmbPersonIDU.Text) select s).First();

dtpStartDateU.Value = student.Sdate;

// Update the Qualification Code Combo Box display var qualcodes = (from q in DB.Qualifications select q.QCode).ToList();

cmbQualificationCodeU.DisplayMember = "QCode"; cmbQualificationCodeU.ValueMember = "QCode"; cmbQualificationCodeU.DataSource = qualcodes;

//Put the correct Qualification Code in the Combo Box int codeCount = 0; int theCode = 0; foreach (string code in qualcodes) { if (code == student.QCode) { theCode = codeCount; } codeCount++; } cmbQualificationCodeU.SelectedIndex = theCode;

// Lookup the selected courses name and put it in the adjacent label // on the form var qualname = (from n in DB.Qualifications where n.QCode == cmbQualificationCodeU.SelectedItem.ToString() select n.QName).First(); lblQNameU.Text = qualname; } else if (MainMenuForm.MenuChoice == "Teacher") { // Select the required data var teacher = (from t in DB.Teachers where t.TID == Convert.ToInt32(cmbPersonIDU.Text) select t.RegNo).First();

txtTeacherRegU.Text = teacher; } else if (MainMenuForm.MenuChoice == "Administrator") { // Select the required data var admin = (from a in DB.Administrations where a.AID == Convert.ToInt32(cmbPersonIDU.Text) select a.Role).First();

txtAdminRoleU.Text = admin; } else { throw new NotSupportedException(); } } // This method fills in the Update screen data properties based on // the criteria set by the Student ID Combo box selection. The script that

Page 39: School System C# Code

// performs this has been moved to the selectTheRecord method. private void cmbStudentIDU_SelectedIndexChanged(object sender, EventArgs e) { selectTheRecord(); }

// This section contains a series of methods that tests the data entry // fields for both the Add and Update Tabs. Each method tests what is the // current screen is and creates an error message if required. They are // activated by the Add and Update Button events.

// This method tests the First Name to make sure that it is not blank private bool ValidFirstName (string firstName, string tab) { if(firstName != "") { if (tab == "Add") { lblFirstNameMessageA.Text = ""; } else if (tab == "Update") { lblFirstNameMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblFirstNameMessageA.Text = "Please enter a first name"; } else if(tab == "Update") { lblFirstNameMessageU.Text = "Please enter a first name"; } return false; } }

// This method tests the Last Name to make sure that it is not blank private bool ValidLastName(string lastName, string tab) { if (lastName != "") { if (tab == "Add") { lblLastNameMessageA.Text = ""; } else if (tab == "Update") { lblLastNameMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblLastNameMessageA.Text = "Please enter a last name"; } else if (tab == "Update") { lblLastNameMessageU.Text = "Please enter a last name";

Page 40: School System C# Code

} return false; } }

// This method tests the birth date to make sure it is not the current // date - ie, it hasn't been overlooked private bool BirthNotToday(DateTime dob, string tab) { if (dob != DateTime.Today) { if (tab == "Add") { lblDOBMessageA.Text = ""; } else if (tab == "Update") { lblDOBMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblDOBMessageA.Text = "Please enter the correct birth date"; } else if (tab == "Update") { lblDOBMessageU.Text = "Please enter the correct birth date"; } return false; } }

// This method tests the Phone to make sure that it is not blank private bool ValidPhone(string phone, string tab) { if (phone != "") { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblPhoneMessageA.Text = "Please enter a phone number"; } else if (tab == "Update") { lblPhoneMessageU.Text = "Please enter a phone number"; } return false; } }

// This method tests the phone number to make sure that it is a numeric

Page 41: School System C# Code

private bool ValidPhoneNumber(string phoneNumber, string tab) { if (tab == "Add") { int n1; bool isNumber = int.TryParse(txtPhoneA.Text, out n1); if (isNumber == true) { lblPhoneMessageA.Text = ""; return true; } else { lblPhoneMessageA.Text = "Please enter just numbers for phone number"; return false; } }

else //if (tab == "Update") { int n1; bool isNumber = int.TryParse(txtPhoneU.Text, out n1); if (isNumber == true) { lblPhoneMessageU.Text = ""; return true; } else { lblPhoneMessageU.Text = "Please enter just numbers for phone number"; return false; }

} }

// This method tests the phone number entry to check that it is only 10 characters long private bool ValidPhoneNumberLength(string phone, string tab) { if (phone.Length == 10) { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblPhoneMessageA.Text = "Please enter just 10 digits for phone number"; } else if (tab == "Update") { lblPhoneMessageU.Text = "Please enter just 10 digits phone number";

Page 42: School System C# Code

} return false; } }

// Check that the right telephone area code is selected for the right state. private bool ValidPhoneForState(string state, string phone, string tab) { if ((state == "NSW" | state == "ACT") & int.Parse(phone.Substring(0, 2)) == 02) { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; } else if (state == "VIC" & int.Parse(phone.Substring(0, 2)) == 03) { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; } else if (state == "QLD" & int.Parse(phone.Substring(0, 2)) == 07) { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; } else if (state == "SA" & int.Parse(phone.Substring(0, 2)) == 08) { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; } else if (state == "WA" & int.Parse(phone.Substring(0, 2)) == 08) { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = "";

Page 43: School System C# Code

} return true; } else if (state == "NT" & int.Parse(phone.Substring(0, 2)) == 08) { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; } else if (int.Parse(phone.Substring(0, 2)) == 04) // Mobile Phone { if (tab == "Add") { lblPhoneMessageA.Text = ""; } else if (tab == "Update") { lblPhoneMessageU.Text = ""; } return true; }

else { switch (state) { case "NSW": case "ACT": if (tab == "Add") { lblPhoneMessageA.Text = "Please change the Area Code to 02"; } else if (tab == "Update") { lblPhoneMessageU.Text = "Please change the Area Code to 02"; } break; case "VIC": case "TAS": if (tab == "Add") { lblPhoneMessageA.Text = "Please change the Area Code to 03"; } else if (tab == "Update") { lblPhoneMessageU.Text = "Please change the Area Code to 03"; }; break; case "QLD": if (tab == "Add") { lblPhoneMessageA.Text = "Please change the Area Code to 07"; } else if (tab == "Update") { lblPhoneMessageU.Text = "Please change the Area Code to 07"; } break; case "NT":

Page 44: School System C# Code

case "SA": case "WA": if (tab == "Add") { lblPhoneMessageA.Text = "Please change the Area Code to 08"; } else if (tab == "Update") { lblPhoneMessageU.Text = "Please change the Area Code to 08"; }; break; case "": if (tab == "Add") { lblPhoneMessageA.Text = "Please select a State to verify the area code"; } else if (tab == "Update") { lblPhoneMessageU.Text = "Please select a State to verify the area code"; } break; default: throw new NotSupportedException(); } return false; } }

// This method tests the address1 to make sure that it is not blank private bool ValidAddress1(string address1, string tab) { if (address1 != "") { if (tab == "Add") { lblAddress1MessageA.Text = ""; } else if (tab == "Update") { lblAddress1MessageU.Text = ""; } return true; } else { if (tab == "Add") { lblAddress1MessageA.Text = "Please enter an address"; } else if (tab == "Update") { lblAddress1MessageU.Text = "Please enter an address"; } return false; } }

// This method tests the suburb to make sure that it is not blank private bool ValidSuburb(string suburb, string tab) { if (suburb != "") {

Page 45: School System C# Code

if (tab == "Add") { lblSuburbMessageA.Text = ""; } else if (tab == "Update") { lblSuburbMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblSuburbMessageA.Text = "Please enter an suburb"; } else if (tab == "Update") { lblSuburbMessageU.Text = "Please enter an suburb"; } return false; } }

// This method tests the state to make sure that it is not blank private bool ValidState(string state, string tab) { if (state != "") { if (tab == "Add") { lblStateMessageA.Text = ""; } else if (tab == "Update") { lblStateMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblStateMessageA.Text = "Please select a state"; } else if (tab == "Update") { lblStateMessageU.Text = "Please select a state"; } return false; }

} // This method tests the postcode to make sure that it is not blank private bool ValidPostcode(string postcode, string tab) { if (postcode != "") { if (tab == "Add") { lblPostcodeMessageA.Text = ""; } else if (tab == "Update") { lblPostcodeMessageU.Text = "";

Page 46: School System C# Code

} return true; } else { if (tab == "Add") { lblPostcodeMessageA.Text = "Please enter a postcode"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Please enter a postcode"; } return false; } }

// This method tests the postcode to make sure that it is a numeric private bool ValidPostcodeNumber(string postcode, string tab) { if (tab == "Add") { int n1; bool isNumber = int.TryParse(txtPostcodeA.Text, out n1);

if (isNumber == true) { lblPostcodeMessageA.Text = ""; return true; } else { lblPostcodeMessageA.Text = "Please enter a numeric value for postcode"; return false; } } else // tab = Update { int n1; bool isNumber = int.TryParse(txtPostcodeU.Text, out n1);

if (isNumber == true) { lblPostcodeMessageU.Text = ""; return true; } else { lblPostcodeMessageU.Text = "Please enter a numeric value for postcode"; return false; } } }

// Check that the right postcode is selected for the right state. private bool ValidPostcodeForState(string state, string postcode, string tab) { if (state == "NT" & int.Parse(postcode) >= 800 & int.Parse(postcode) <= 899) { if (tab == "Add") { lblPostcodeMessageA.Text = ""; }

Page 47: School System C# Code

else if (tab == "Update") { lblPostcodeMessageU.Text = ""; } return true; } else if ((state == "NSW" | state == "ACT") & int.Parse(postcode) >= 2000 & int.Parse(postcode) <= 2999) { if (tab == "Add") { lblPostcodeMessageA.Text = ""; } else if (tab == "Update") { lblPostcodeMessageU.Text = ""; } return true; } else if (state == "VIC" & int.Parse(postcode) >= 3000 & int.Parse(postcode) <= 3999) { if (tab == "Add") { lblPostcodeMessageA.Text = ""; } else if (tab == "Update") { lblPostcodeMessageU.Text = ""; } return true; } else if (state == "QLD" & int.Parse(postcode) >= 4000 & int.Parse(postcode) <= 4999) { if (tab == "Add") { lblPostcodeMessageA.Text = ""; } else if (tab == "Update") { lblPostcodeMessageU.Text = ""; } return true; } else if (state == "SA" & int.Parse(postcode) >= 5000 & int.Parse(postcode) <= 5999) { if (tab == "Add") { lblPostcodeMessageA.Text = ""; } else if (tab == "Update") { lblPostcodeMessageU.Text = ""; } return true; } else if (state == "WA" & int.Parse(postcode) >= 6000 & int.Parse(postcode) <= 6999) { if (tab == "Add") { lblPostcodeMessageA.Text = ""; }

Page 48: School System C# Code

else if (tab == "Update") { lblPostcodeMessageU.Text = ""; } return true; }

else { switch (state) { case "NT": if (tab == "Add") { lblPostcodeMessageA.Text = "Postcode must be between 0800 and 0899"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Postcode must be between 0800 and 0899"; } break; case "NSW": case "ACT": if (tab == "Add") { lblPostcodeMessageA.Text = "Postcode must be between 2000 and 2999"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Postcode must be between 2000 and 2999"; } break; case "VIC": if (tab == "Add") { lblPostcodeMessageA.Text = "Postcode must be between 3000 and 3999"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Postcode must be between 3000 and 3999"; } break; case "QLD": if (tab == "Add") { lblPostcodeMessageA.Text = "Postcode must be between 4000 and 4999"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Postcode must be between 4000 and 4999"; } break; case "SA": if (tab == "Add") { lblPostcodeMessageA.Text = "Postcode must be between 5000 and 5999";

Page 49: School System C# Code

} else if (tab == "Update") { lblPostcodeMessageU.Text = "Postcode must be between 5000 and 5999"; } break; case "WA": if (tab == "Add") { lblPostcodeMessageA.Text = "Postcode must be between 6000 and 6999"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Postcode must be between 6000 and 6999"; } break; case "TAS": if (tab == "Add") { lblPostcodeMessageA.Text = "Postcode must be between 7000 and 7999"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Postcode must be between 7000 and 7999"; } break; case "": // make sure that there is something entered for state if (tab == "Add") { lblPostcodeMessageA.Text = "Please select a State to verify the postcode"; } else if (tab == "Update") { lblPostcodeMessageU.Text = "Please select a State to verify the postcode"; } break; default: throw new NotSupportedException(); } return false; } }

// Check that data has been entered for the teachers registration private bool validateRegistration(string registrationNo, string tab) { if (registrationNo != "") { if (tab == "Add") { lblTeacherRegMessageA.Text = ""; } else if (tab == "Update") { lblTeacherRegMessageU.Text = ""; } return true; }

Page 50: School System C# Code

else { if (tab == "Add") { lblTeacherRegMessageA.Text = "Please enter a registration number"; } else if (tab == "Update") { lblTeacherRegMessageU.Text = "Please enter a registration number"; } return false; } } // Check that data has been entered for the administrator role private bool validateRole(string roleName, string tab) { if (roleName != "") { if (tab == "Add") { lblAdminRoleMessageA .Text = ""; } else if (tab == "Update") { lblAdminRoleMessageU.Text = ""; } return true; } else { if (tab == "Add") { lblAdminRoleMessageA.Text = "Please enter an admin role"; } else if (tab == "Update") { lblAdminRoleMessageU.Text = "Please enter an admin role"; } return false; } }

// This method adds a Person to the Person and // Student/Teacher/Administrator tables // once the data on the form has been validated. private void btnAddA_Click(object sender, EventArgs e) { try { // Indicate that this is the Add Tab for Error Message control string theTab = "Add";

// This section of code applies to the data entry fields // for the Person table

// Test that a first name has been entered if(!ValidFirstName(txtFirstNameA.Text, theTab)) { return; }

// Test that a last name has been entered if (!ValidLastName(txtLastNameA.Text, theTab)) { return;

Page 51: School System C# Code

}

// Test that a proper birth date has been entered if (!BirthNotToday(dtpDateOfBirthA.Value, theTab)) { return; }

// Test that a phone number has been entered if (!ValidPhone(txtPhoneA.Text, theTab)) { return; }

// Test that the phone number is numeric if (!ValidPhoneNumber(txtPhoneA.Text, theTab)) { return; }

// Test that the phone number has only 10 digits if (!ValidPhoneNumberLength(txtPhoneA.Text, theTab)) { return; }

// Test that the correct area code for phone number has been entered if (!ValidPhoneForState(cmbStateA.Text, txtPhoneA.Text, theTab)) { return; }

// Test that address1 has been entered if (!ValidAddress1(txtAddress1A.Text, theTab)) { return; }

// Test that a suburb has been entered if (!ValidSuburb(txtSuburbA.Text, theTab)) { return; }

// Test that a state has been entered if (!ValidState(cmbStateA.Text, theTab)) { return; }

// Test that a postcode has been entered if (!ValidPostcode(txtPostcodeA.Text, theTab)) { return; }

// Test that the postcode is a numeric if (!ValidPostcodeNumber(txtPostcodeA.Text, theTab)) { return; }

// Test that a correct postcode has been entered if (!ValidPostcodeForState(cmbStateA.Text, txtPostcodeA.Text, theTab)) {

Page 52: School System C# Code

return; }

// Test that a Teacher Registration has been entered if (MainMenuForm.MenuChoice == "Teacher") { if (!validateRegistration(txtTeacherRegA.Text, theTab)) { return; } }

// Test that an admin role has been entered if (MainMenuForm.MenuChoice == "Administrator") { if (!validateRole(txtAdminRoleA.Text, theTab)) { return; } } // Create a new person object for the student and add its properties var newPerson = new Person(); newPerson.FName = txtFirstNameA.Text.Trim(); newPerson.LName = txtLastNameA.Text.Trim(); newPerson.DOB = dtpDateOfBirthA.Value; newPerson.Phone = txtPhoneA.Text; newPerson.Add1 = txtAddress1A.Text.Trim(); newPerson.Add2 = txtAddress2A.Text.Trim(); newPerson.Suburb = txtSuburbA.Text.Trim(); newPerson.State = cmbStateA.SelectedItem.ToString(); newPerson.Postcode = txtPostcodeA.Text.Trim(); newPerson.Type = MainMenuForm.MenuChoice; // either Student, Teacher or Administrator

// Add the new person to the database DB.Persons.InsertOnSubmit(newPerson); DB.SubmitChanges();

// Get the newly created person ID number var newPersonID = newPerson.ID;

if (MainMenuForm.MenuChoice == "Student") { // Create new student object and add its properties var newStudent = new Student(); newStudent.SID = newPersonID; newStudent.Sdate = dtpStartDateA.Value; newStudent.QCode = cmbQualificationCodeA.SelectedItem.ToString();

// Add the new student specific data to the database DB.Students.InsertOnSubmit(newStudent); DB.SubmitChanges();

// Setup the required courses for the Student_Course Table try { var courseNumbers = (from c in DB.Qualification_Courses where c.QCode == cmbQualificationCodeA.SelectedItem.ToString() select c.CID).ToList();

int index = 0; foreach (int c in courseNumbers)

Page 53: School System C# Code

{ var newStudentCourse = new Student_Course(); newStudentCourse.CID = courseNumbers[index]; newStudentCourse.SID = newPersonID; newStudentCourse.Mark = 0; DB.Student_Courses.InsertOnSubmit(newStudentCourse); DB.SubmitChanges(); index++;

} }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } } else if (MainMenuForm.MenuChoice == "Teacher") { // Create new teacher object and add its properties var newTeacher = new Teacher(); newTeacher.TID = newPersonID; newTeacher.RegNo = txtTeacherRegA.Text.Trim(); newTeacher.Password = "teacher"; // A new Default password

// Add the new teacher specific data to the database DB.Teachers.InsertOnSubmit(newTeacher); DB.SubmitChanges();

lblAddMessage.Text = "Teacher ID " + newPersonID + " was added with a temporary password 'teacher'. \r\nPlease get " + txtFirstNameA.Text + " to change this password as soon as possible"; } else if (MainMenuForm.MenuChoice == "Administrator") { // Create new administrator object and add its properties var newAdministration = new Administration(); newAdministration.AID = newPersonID; newAdministration.Role = txtAdminRoleA.Text.Trim(); newAdministration.Password = "adminis"; // A new default password

// Add the new student specific data to the database DB.Administrations.InsertOnSubmit(newAdministration); DB.SubmitChanges();

lblUpdateMessage.Text = "Administrator ID " + newPersonID + " was added with a temporary password 'adminis'. \r\nPlease get " + txtFirstNameA.Text + " to change this password as soon as possible"; } else { throw new NotSupportedException(); }

lblUpdateMessage.Text = "ID " + newPersonID + " was added";

UpdateData(updated); }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

Page 54: School System C# Code

// This method updates the Person and Student/Teacher/Administration // table once the data has been validated. private void btnUpdateU_Click(object sender, EventArgs e) { // Indicate that this is the Update Tab for Error Message control string theTab = "Update"; try { // Test that a first name has been entered if (!ValidFirstName(txtFirstNameU.Text, theTab)) { return; }

// Test that a last name has been entered if (!ValidLastName(txtLastNameU.Text, theTab)) { return; }

// Test that a proper birth date has been entered if (!BirthNotToday(dtpDateOfBirthU.Value, theTab)) { return; }

// Test that a phone number has been entered if (!ValidPhone(txtPhoneU.Text, theTab)) { return; }

// Test that the phone number is numeric if (!ValidPhoneNumber(txtPhoneU.Text, theTab)) { return; }

// Test that the phone number has only 10 digits if (!ValidPhoneNumberLength(txtPhoneU.Text, theTab)) { return; }

// Test that the correct area code for phone number has been entered if (!ValidPhoneForState(cmbStateU.Text, txtPhoneU.Text, theTab)) { return; }

// Test that address1 has been entered if (!ValidAddress1(txtAddress1U.Text, theTab)) { return; }

// Test that a suburb has been entered if (!ValidSuburb(txtSuburbU.Text, theTab)) { return; }

// Test that a state has been entered if (!ValidState(cmbStateU.Text, theTab)) {

Page 55: School System C# Code

return; }

// Test that a postcode has been entered if (!ValidPostcode(txtPostcodeU.Text, theTab)) { return; }

// Test that the postcode is a numeric if (!ValidPostcodeNumber(txtPostcodeU.Text, theTab)) { return; }

// Test that a correct postcode has been entered if (!ValidPostcodeForState(cmbStateU.Text, txtPostcodeU.Text, theTab)) { return; }

// Test that a Teacher Registration has been entered if (MainMenuForm.MenuChoice == "Teacher") { if (!validateRegistration(txtTeacherRegU.Text, theTab)) { return; } }

// Test that an admin role has been entered if (MainMenuForm.MenuChoice == "Administrator") { if (!validateRole(txtAdminRoleU.Text, theTab)) { return; } }

// Update the student record in the person database var personList = (from p in DB.Persons where p.ID == Convert.ToInt32(cmbPersonIDU.Text) select p).First();

personList.FName = txtFirstNameU.Text.Trim(); personList.LName = txtLastNameU.Text.Trim(); personList.DOB = dtpDateOfBirthU.Value; personList.Phone = txtPhoneU.Text.Trim(); personList.Add1 = txtAddress1U.Text.Trim(); personList.Add2 = txtAddress2U.Text.Trim(); personList.Suburb = txtSuburbU.Text.Trim(); personList.State = cmbStateU.SelectedItem.ToString(); personList.Postcode = txtPostcodeU.Text.Trim();

// Save the changes that were made DB.SubmitChanges();

// Refresh the bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Persons);

if (MainMenuForm.MenuChoice == "Student") { // Update the student record in the Student database var studentList = (from s in DB.Students where s.SID == Convert.ToInt32(cmbPersonIDU.Text)

Page 56: School System C# Code

select s).First();

studentList.Sdate = dtpStartDateU.Value; studentList.QCode = cmbQualificationCodeU.SelectedItem.ToString();

// Save the changes that were made DB.SubmitChanges();

// Refresh the bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Students); } else if (MainMenuForm.MenuChoice == "Teacher") { // Update the teacher object and add its properties var teacherList = (from t in DB.Teachers where t.TID == Convert.ToInt32(cmbPersonIDU.Text) select t).First();

teacherList.RegNo = txtTeacherRegU.Text.Trim();

// Save the changes that were made DB.SubmitChanges();

// Refresh the bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Teachers); } else if (MainMenuForm.MenuChoice == "Administrator") { // Update the administrator object and add its properties var adminList = (from a in DB.Administrations where a.AID == Convert.ToInt32(cmbPersonIDU.Text) select a).First();

adminList.Role = txtAdminRoleU.Text.Trim();

// Save the changes that were made DB.SubmitChanges();

// Refresh the bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Administrations); } else { throw new NotSupportedException(); }

lblUpdateMessage.Text = "ID " + cmbPersonIDU.Text + " was updated";

updated = true; // Do not reset the Person ID combo box UpdateData(updated); selectTheRecord(); updated = false; }

catch (Exception Ex) { MessageBox.Show(Ex.Message); } }

// This method deletes the selected Person id in the update table's // id combo box. private void btnDeleteU_Click(object sender, EventArgs e) { try

Page 57: School System C# Code

{

DialogResult d = MessageBox.Show("Are you sure you want to delete this record?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (d == DialogResult.Yes) { int idToDelete = (int)cmbPersonIDU.SelectedValue;

// Get the record that matches the criteria in the ID // combo box var deletedPerson = (from p in DB.Persons where p.ID == idToDelete select p).First();

DB.Persons.DeleteOnSubmit(deletedPerson);

if (MainMenuForm.MenuChoice == "Student") { var deletedStudent = (from s in DB.Students where s.SID == idToDelete select s).First();

DB.Students.DeleteOnSubmit(deletedStudent); MessageBox.Show("Student deleted"); } else if (MainMenuForm.MenuChoice == "Teacher") { var deletedTeacher = (from t in DB.Teachers where t.TID == idToDelete select t).First();

DB.Teachers.DeleteOnSubmit(deletedTeacher);

MessageBox.Show("Teacher deleted"); } else if (MainMenuForm.MenuChoice == "Administrator") { // Delete the administrator record var deletedAdministration = (from t in DB.Administrations where t.AID == idToDelete select t).First();

DB.Administrations.DeleteOnSubmit(deletedAdministration); } else { throw new NotSupportedException(); } DB.SubmitChanges(); UpdateData(updated); }

else if (d == DialogResult.No) { MessageBox.Show("Delete operation cancelled"); } }

catch (Exception Ex) {

Page 58: School System C# Code

MessageBox.Show(Ex.Message); } }

// Update the Qualification Name label every time the Combo Box value changes private void cmbQualificationCodeA_SelectedIndexChanged(object sender, EventArgs e) { // Lookup the selected Qualification name and put it in the adjacent label // on the form var qualname = (from n in DB.Qualifications where n.QCode == cmbQualificationCodeA.SelectedItem.ToString() select n.QName).First(); lblQNameA.Text = qualname; }

// Update the Qualification Name label every time the Combo Box value changes private void cmbQualificationCodeU_SelectedIndexChanged(object sender, EventArgs e) { var qualname = (from n in DB.Qualifications where n.QCode == cmbQualificationCodeU.SelectedItem.ToString() select n.QName).First(); lblQNameU.Text = qualname; }

// This method exits from the Add screen private void btnExitA_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

// This method exits from the Update screen private void btnExitU_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; } }}

Page 59: School System C# Code

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.Linq;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace SchoolSystem{ // Written by : Paul Smyth // Date of last issue : 9/9/2015 // // This form allows the user to update his/her password. // It prompts the user to input a new password twice, the // second time is to verify that the first password was typed as // intended. Once the new password has been validated, the // Teacher/Administration table is updated. // // It takes the static variable personID from the logonForm // to indicate theID of the user that has logged on to the system. // This information is used to select the correct record from // the teacher / Administration table to receive the password // update. public partial class ChangePasswordForm : Form { SchoolDataClassesDataContext DB = new SchoolDataClassesDataContext(); public ChangePasswordForm() { InitializeComponent(); }

private void ChangePasswordForm_Load(object sender, EventArgs e) { clearPasswords(); // clear the text fields

lblPasswordMessage.Text = "Enter a new 7 character password.\r\nThen re-enter it for verification purposes";

//Set up ToolTips for the form toolTip1.SetToolTip(txtPassword1, "Enter a new 7 character password"); toolTip1.SetToolTip(txtPassword2, "Re-enter the new password \r\nfor verification purposes"); toolTip1.SetToolTip(btnExit, "Return to Main Menu"); toolTip1.SetToolTip(btnUpdate, "Update the changed password");

}

// This method tests that the entered password is 7 characters long private bool validPasswordLength(string thePassword) { if (thePassword.Length != 7) { lblPasswordMessage.Text = "The password must be seven characters long. \r\nPlease try again"; clearPasswords(); return false; } else { lblPasswordMessage.Text = "";

Page 60: School System C# Code

return true; } }

// This method compares the two entered passwords private bool validComparePasswords(string password1, string password2) { if (txtPassword1.Text != txtPassword2.Text) { lblPasswordMessage.Text = "The re-entered pasword is not identical. \r\nPlease try again"; clearPasswords(); return false; } else { lblPasswordMessage.Text = ""; return true; } }

// This method clears the password text fields internal void clearPasswords() { txtPassword1.Clear(); txtPassword2.Clear(); }

private void btnExit_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.No; }

// This method checks the data input and if it is ok, // write it to the Persons table. private void btnUpdate_Click(object sender, EventArgs e) { // Test to see that the first password entry is the required length if (!validPasswordLength(txtPassword1.Text)) { return; }

// Test to see if the two password entries are identical if (!validComparePasswords(txtPassword1.Text, txtPassword2.Text)) { return; }

// Update the password entry in the table if (LogonForm.personType == "Administrator") { var newPassword = (from p in DB.Administrations where p.AID == Convert.ToInt32(LogonForm.personID) select p).First();

newPassword.Password = txtPassword1.Text;

// Save the changes that were made DB.SubmitChanges();

// Refresh the Bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Courses); }

Page 61: School System C# Code

else if (LogonForm.personType == "Teacher") { var newPassword = (from p in DB.Teachers where p.TID == Convert.ToInt32(LogonForm.personID) select p).First();

newPassword.Password = txtPassword1.Text;

// Save the changes that were made DB.SubmitChanges();

// Refresh the Bound controls DB.Refresh(RefreshMode.OverwriteCurrentValues, DB.Courses); }

lblPasswordMessage.Text = "Password has been successfully updated"; } }}