Employee Database Program

EmployeeDatabase EmployeeDatabaseXSD EmployeeDatabaseMainScreen

EditEmployeeScreen ViewDeparmentsScreen

Hello again. I’ll be expanding more on using a database with C# .NET with this project. Again this program is meant for a small company since it’s using an Access Database to store the data. I’ll be putting out an SQL version at a later time for bigger companies that might have data bigger than 2GB.

I’ve been working on an employee database for a client. This is the “almost finished” version of it. I didn’t really want to wait and put the final product up on this blog because of all the little details gone into it so far. I’ll make another post later on with the finished product.

In the program you have the ability to track employee information such as employee ID, what department they’re in, first/last name, salary, address, state, zip, etc.., along with some other items you can see from the screenshots below. You can also edit employee information after it’s been entered along with a drag and drop feature for an employee photo.

You also have the ability to track the various departments in your company. The last piece I was talking about earlier is the ability to edit the departments after they’ve been entered. This is the last piece I have to get working. The client didn’t need this particular functionality, however, it’s something I will include in the final piece.

Remember you can download the source to this program or the actual program itself on my downloads page.

Cheers

Tails8

MainForm Code

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

//This application is used to keep track of employees and the departments in a company. The application is
//tied to a Microsoft Access Database.

namespace EmployeeDatabase
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //This loads data into the mainForm datagrid getting data from the employeeDatabaseDataSet.EmployeeDeptRegister dataset.
            this.employeeDeptRegisterTableAdapter.Fill(this.employeeDatabaseDataSet.EmployeeDeptRegister);

            //This loads data into the Department combo box getting data from from the employeeDatabaseDataSet.Departments dataset.
            this.departmentsTableAdapter.Fill(this.employeeDatabaseDataSet.Departments);
              
            //****Menu strip item lambda expressions****
            //Lambda expression for the File -> Exit menu strip item.
            exitToolStripMenuItem.Click += (from, ea) => this.Close();

            //Lambda expression for the Edit -> Edit Employee menu strip item.
            editEmployeeToolStripMenuItem.Click += (from, ea) => EditEmployee();

            //Lambda expression for the Edit -> Delete Employee menu strip item.
            deleteEmployeeToolStripMenuItem.Click += (from, ea) => DeleteEmployee();

            //Lambda expression for the Departments -> View Departments menu strip item.
            viewDepartmentsToolStripMenuItem.Click += (from, ea) =>
                {
                    //Showing the departments form and refreshing the mainForm combobox upon the departments form exit.
                    DepartmentsForm viewDepartments = new DepartmentsForm();
                    if (viewDepartments.ShowDialog() == DialogResult.OK)
                        this.departmentsTableAdapter.Fill(this.employeeDatabaseDataSet.Departments);
                };
        
            //****Button item lambda expressions****
            //Lambda expression for the Exit button to close the whole program.
            mainFormExitButton.Click += (from, ea) => this.Close();

            //Lambda expression for the Add Employee button.
            mainFormAddEmployeeButton.Click += (from, ea) => AddEmployee();

            //Lambda expression for the Edit Employee button.
            mainFormEditEmployeeButton.Click += (from, ea) => EditEmployee();

            //Lambda expression for the Delete Employee button.
            mainFormDeleteEmployeeButton.Click += (from, ea) => DeleteEmployee();
  
            //****Context menu strip item lambda expressions****
            //Lambda expression for the Edit Employee context menu strip item.
            editEmployeeContextMenuStripItem.Click += (from, ea) => EditEmployee();

            //Lambda expression for the Delete Employee context menu strip item.
            deleteEmployeeContextMenuStripItem.Click += (from, ea) => DeleteEmployee();

            //Making it so the user cannot change the sorting of the mainFormDataGridView. Reason for this is the ability to edit the employee
            //is tied to their employee ID which is tied to the database rowIndex. So sorting the data grid would mess this up.
            foreach (DataGridViewColumn column in mainFormDataGridView.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }

        }

        //Method that brings up the context menu strip when the mainForm datagrid is right-clicked on.
        private void mainFormDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            //Checking to see if the right mouse button was pressed.
            if (e.Button == MouseButtons.Right)
            {
                //Making sure that the mouse is over a row during the mouse button press.
                if (e.RowIndex >= 0)
                {
                    //Highlighting the employee's last name as a visual indicator.
                    mainFormDataGridView.CurrentCell = mainFormDataGridView.Rows[e.RowIndex].Cells[0];

                    //Getting the mouse pointer location information.
                    Point mousePoint = mainFormDataGridView.PointToClient(Cursor.Position);
                    DataGridView.HitTestInfo hitTestInfo = mainFormDataGridView.HitTest(
                        mousePoint.X, mousePoint.Y);

                    //Displaying the context menu strip.       
                    if (hitTestInfo.Type == DataGridViewHitTestType.Cell)
                        mainFormContextMenuStrip.Show(mainFormDataGridView, mousePoint);
                }
            }
        }

        //Method that takes the user data input and creates a new entry in the database after the Add Employee
        //button or menu item is selected.
        private void AddEmployee()
        {
            //Getting the employee data of birth to use.
            DateTime dateOfBirth;
            DateTime.TryParse(mainFormDateOfBirthDateTimePicker.Value.ToShortDateString(), out dateOfBirth);

            //Adding the employee data into the database. You see null / false values in here because only a
            //certain amount of employee data is needed during the initial creation. If more info is to be added
            //the employee can be edited later.
            employeeRegisterTableAdapter.Insert(
                Convert.ToInt32(mainFormDepartmentComboBox.SelectedValue),
                string.IsNullOrWhiteSpace(mainFormLastNameTextBox.Text) ? null : mainFormLastNameTextBox.Text,
                string.IsNullOrWhiteSpace(mainFormFirstNameTextBox.Text) ? null : mainFormFirstNameTextBox.Text,
                string.IsNullOrWhiteSpace(mainFormEmployeeNotesTextBox.Text) ? null : mainFormEmployeeNotesTextBox.Text,
                null,
                false,
                false,
                dateOfBirth,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);

            //Re-populating the mainForm data grid. Basically refreshing the screen to show the newly entered
            //data.
            this.employeeDeptRegisterTableAdapter.Fill(this.employeeDatabaseDataSet.EmployeeDeptRegister);
        }

        
        //Method that gets called upon when an existing record needs to be edited.
        private void EditEmployee()
        {
            int rowIndex = mainFormDataGridView.CurrentRow.Index;

            if (rowIndex >= 0)
            {
                string registerID = mainFormDataGridView[0, rowIndex].Value.ToString();     //Getting the value of the employee ID.
                string deptName = mainFormDataGridView[3, rowIndex].Value.ToString();       //Getting the value of the department name.

                int bindingSourceId = employeeDeptRegisterBindingSource.Find("registerID", registerID);     //Getting the index of the employee.
                int deptBindingSourceId = departmentsBindingSource.Find("departmentName", deptName);        //Getting the index of the dept the employee is a member of.

                if (bindingSourceId >= 0)
                {
                    EditEmployeeForm editEmployee = new EditEmployeeForm();
                    editEmployee.Position = bindingSourceId;
                    editEmployee.DeptPosition = deptBindingSourceId;
                    if (editEmployee.ShowDialog() == DialogResult.OK)
                    {
                        this.employeeDeptRegisterTableAdapter.Fill(this.employeeDatabaseDataSet.EmployeeDeptRegister);
                        mainFormDataGridView.ClearSelection();
                        mainFormDataGridView.Rows[rowIndex].Selected = true;
                    }
                }
            }
        }

        //Method that gets called upon when am existing record needs to be deleted.
        private void DeleteEmployee()
        {
            if (mainFormDataGridView.CurrentRow.Index >= 0)
            {
                //Getting the string value of the employee ID which is also used to locate the database record.
                string registerIDString = mainFormDataGridView.Rows[mainFormDataGridView.CurrentRow.Index].
                    Cells[0].Value.ToString();

                //Getting the selected record last name.
                string lastName = mainFormDataGridView.Rows[mainFormDataGridView.CurrentRow.Index].
                    Cells[1].Value.ToString();

                //Getting the selected record first name.
                string firstName = mainFormDataGridView.Rows[mainFormDataGridView.CurrentRow.Index].
                    Cells[2].Value.ToString();

                //Converting the registerIDString variable to an int to use when removing the database record.
                int registerID = -1;
                if (int.TryParse(registerIDString, out registerID))
                {
                    //Displaying a dialog box asking the user if they are sure.
                    if (DialogResult.Yes == MessageBox.Show("Are you sure you want to remove employee ID: " + registerIDString +
                        " " + lastName + " " + firstName, "Delete Entry", MessageBoxButtons.YesNo))
                    {
                        //Deleting the employee record and updating the mainForm data grid.
                        //NOTE: I had to modify the table adaptor delete method to only take the registerID as the only
                        //parameter. Since this is the only thing needed that ties the entry to the database record.
                        employeeRegisterTableAdapter.Delete(registerID);
                        this.employeeDeptRegisterTableAdapter.Fill(this.employeeDatabaseDataSet.EmployeeDeptRegister);
                    }
                }
            }
        }
    }
}

EditEmployeeForm Code

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

namespace EmployeeDatabase
{
    public partial class EditEmployeeForm : Form
    {
        public int Position { get; set; }
        public int DeptPosition { get; set; } 

        public EditEmployeeForm()
        {
            Position = -1;  
            DeptPosition = -1;
            InitializeComponent();
            this.employeePhotographPictureBox.AllowDrop = true;     //Enabling the ability to drag and drop on the Employee Picture box.
        }

        private void EditEmployeeForm_Load(object sender, EventArgs e)
        {
            //This line of code loads data into the the Department combobox from the employeeDatabaseDataSet1.Departments data source.
            this.departmentsTableAdapter1.Fill(this.employeeDatabaseDataSet1.Departments); 

            //This line of code loads data into the form from the employeeDatabaseDataSet1.EmployeeRegister data source..
            this.employeeRegisterTableAdapter1.Fill(this.employeeDatabaseDataSet1.EmployeeRegister);

            //****Button item lambda expressions****
            //Lambda expression for the Cancel button.
            editEmployeeFormCancelButton.Click += (from, ea) => this.Close();

            //Lambda expression for the Save button. This takes care of saving any changed data back to the database by clicking on this button.
            editEmployeeFormSaveButton.Click += (from, ea) =>
            {
                this.employeeRegisterBindingSource.EndEdit();       //Ending all editing for the EmployeeRegister dataset.
                this.Validate();
                this.tableAdapterManager1.UpdateAll(this.employeeDatabaseDataSet1);     //Updating all the data to the main EmployeeDatabaseDataSet.
            };
       
            if (Position >= 0)
            {
                this.employeeRegisterBindingSource.Position = Position;
                this.departmentsBindingSource.Position = DeptPosition;
            }
        }

        //This method along with the DragEnter method takes care of the drag an drop functionality of the Employee Photograph picturebox.
        private void employeePhotographPictureBox_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (filePaths.Length > 0)
                {
                    string path = filePaths[0];
                    try
                    {
                        using (MemoryStream memoryStream = new MemoryStream(File.ReadAllBytes(path)))
                        {
                            Image tempImage = Image.FromStream(memoryStream);
                            employeePhotographPictureBox.Image = new Bitmap(tempImage);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error loading the file: " + ex.Message);
                    }
                }
            }
        }

        private void employeePhotographPictureBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }
    }
}

DepartmentsForm Code

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

namespace EmployeeDatabase
{
    public partial class DepartmentsForm : Form
    {
        public DepartmentsForm()
        {
            InitializeComponent();
        }

        //This method is for reference. Can be removed later.
        private void departmentsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.departmentsBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.employeeDatabaseDataSet);
        }

        private void DepartmentsForm_Load(object sender, EventArgs e)
        {
            //This loads data into the departmentsDataGridView getting data from employeeDatabaseDataSet.Departments table.
            this.departmentsTableAdapter.Fill(this.employeeDatabaseDataSet.Departments);

            //****Menu strip item lambda expressions****
            //Lambda expression for the File -> Exit menu option item.
            exitToolStripMenuItem.Click += (from, ea) => this.Close();

            //Lambda expression for the Edit -> Edit Department menu option item.
            editDepartmentToolStripMenuItem.Click += (from, ea) => EditDepartment();

            //Lambda expression for the Edit -> Delete Department menu option item.
            deleteDepartmentToolStripMenuItem.Click += (from, ea) => DeleteDepartment();

            //****Button item lambda expressions****
            //Lambda expresion when the Exit button is clicked on.
            exitButton.Click += (from, ea) => this.Close();

            //Lambda expression for the Add Department button.
            addDepartmentButton.Click += (from, ea) => AddDepartment();

            //Lambda expression for the Edit Department button.
            editDepartmentButton.Click += (from, ea) => EditDepartment();

            //Lambda expression for the Delete Department button.
            deleteDepartmentButton.Click += (from, ea) => DeleteDepartment();

            //****Context menu strip item lambda expressions****
            editDepartmentContextMenuItem.Click += (from, ea) => EditDepartment();

            deleteDepartmentContextMenuItem.Click += (from, ea) => DeleteDepartment();

            //Making it so the user cannot change the sorting in the main window.
            foreach (DataGridViewColumn column in departmentsDataGridView.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        //Method that brings up the context menu strip when the datagrid is right-clicked on.
        private void departmentsDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            //Checking to see if the right mouse button was pressed.
            if (e.Button == MouseButtons.Right)
            {
                //Making sure that the mouse pointer is over a row during the button press.
                if (e.RowIndex >= 0)
                {
                    //Highlighting the department name as a visual indicator.
                    departmentsDataGridView.CurrentCell = departmentsDataGridView.Rows[e.RowIndex].Cells[1];

                    //Getting the mouse pointer location information.
                    Point mousePoint = departmentsDataGridView.PointToClient(Cursor.Position);
                    DataGridView.HitTestInfo hitTestInfo = departmentsDataGridView.HitTest(mousePoint.X, mousePoint.Y);

                    if (hitTestInfo.Type == DataGridViewHitTestType.Cell)
                        departmentFormContextMenuStrip.Show(departmentsDataGridView, mousePoint);
                }
            }
        }

        //Method used to add a new department when the fields are filled out and the Add button is clicked.
        private void AddDepartment()
        {
            //Inserting the new department info into the database.
            departmentsTableAdapter.Insert(
                string.IsNullOrWhiteSpace(departmentNameTextbox.Text) ? null : departmentNameTextbox.Text,
                string.IsNullOrWhiteSpace(departmentDescriptionTextBox.Text) ? null : departmentDescriptionTextBox.Text,
                string.IsNullOrWhiteSpace(departmentSupervisorTextBox.Text) ? null : departmentSupervisorTextBox.Text);

            //Re-populate the departments data grid.
            this.departmentsTableAdapter.Fill(this.employeeDatabaseDataSet.Departments);
        }

        //Method used to edit an existing department.
        private void EditDepartment()
        {
            //Edit an existing department.
            Console.WriteLine("Edit department test");
        }

        //Method used to delete an existing department.
        private void DeleteDepartment()
        {
            int rowIndex = departmentsDataGridView.CurrentRow.Index;
            if (rowIndex >= 0)
            {
                //Getting the ID and name of the department to delete.
                string departmentID = departmentsDataGridView[0, rowIndex].Value.ToString();
                string departmentName = departmentsDataGridView[1, rowIndex].Value.ToString();
                int bindingSourceID = departmentsBindingSource.Find("departmentID", departmentID);
                
                //Displaying a message asking the user if they're sure to remove the department. If so then the
                //department data is removed from the database.
                if (DialogResult.Yes == MessageBox.Show("Are you sure you want to remove department: " + departmentName, "Delete Department",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    this.departmentsBindingSource.RemoveAt(bindingSourceID);
                    this.tableAdapterManager.UpdateAll(this.employeeDatabaseDataSet);
                    departmentsDataGridView.ClearSelection();
                }
            }
        }
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s