CSharp and Access Database Learn C# By Building a Simple Application


C# and Access Database Premium Video Tutorials : Learn C# By Building a Simple Application.

🎓 Master Visual Basic .NET and Access Database By Building the Point Of Sale System (POS).
ðŸ“ē Enroll Now: https://bit.ly/2WcbRhX

🎓 Recommended For You : YouTube Playlist
✅ Learn C# By Building a Simple Application.

[Screenshot]

[Preview Video]


[Source 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 EmployeeManagement
{
    public partial class Form1 : Form
    {

        private int oneTimeRefresh = 0;

        public Form1()
        {
            InitializeComponent();

            toolStripComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            toolStripComboBox1.Items.Clear();

            List<string> lstItems = new List<string>() { "Top 10", "Top 20", "Top 30", "Top 40", "Top 50", "Select All" };
            toolStripComboBox1.ComboBox.DataSource = lstItems;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'employeeDatabaseDataSet.Departments' table. You can move, or remove it, as needed.
            this.departmentsTableAdapter.Fill(this.employeeDatabaseDataSet.Departments);
            // TODO: This line of code loads data into the 'employeeDatabaseDataSet.JobTitles' table. You can move, or remove it, as needed.
            this.jobTitlesTableAdapter.Fill(this.employeeDatabaseDataSet.JobTitles);
            // TODO: This line of code loads data into the 'employeeDatabaseDataSet.Prefixes' table. You can move, or remove it, as needed.
            this.prefixesTableAdapter.Fill(this.employeeDatabaseDataSet.Prefixes);
            // TODO: This line of code loads data into the 'employeeDatabaseDataSet.Employees' table. You can move, or remove it, as needed.
            this.employeesTableAdapter.Fill(this.employeeDatabaseDataSet.Employees);

            if (this.toolStripComboBox1.Items.Count > 0)
            {
                // Select All : idx = 5 (6 - 1)
                int idx = this.toolStripComboBox1.Items.Count - 1;
                this.toolStripComboBox1.SelectedIndex = idx;
            }

            // <- Begin Setup DataGridView ->

            DataGridView dgv = dataGridView1;

            foreach (DataGridViewColumn col in dgv.Columns)
            {
                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.HeaderCell.Style.Font = new Font("Microsoft Sans Serif", 14.0F, FontStyle.Regular, GraphicsUnit.Pixel);

                col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }

            dgv.RowsDefaultCellStyle.BackColor = Color.FromName("White");
            dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.FromName("GhostWhite");

            // Hide Auto ID Column
            dgv.Columns[0].Visible = false;
            // Employee ID
            dgv.Columns[1].Width = 170;
            dgv.Columns[1].HeaderText = "Employee ID";
            // Reference ID
            dgv.Columns[2].Width = 130;
            dgv.Columns[2].HeaderText = "Reference ID";
            // ID Number
            dgv.Columns[3].Width = 170;
            dgv.Columns[3].HeaderText = "ID Number";
            // Hide Prefix ID Column
            dgv.Columns[4].Visible = false;
            // First Name
            dgv.Columns[5].Width = 170;
            dgv.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgv.Columns[5].HeaderText = "First Name";
            // Last Name
            dgv.Columns[6].Width = 170;
            dgv.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgv.Columns[6].HeaderText = "Last Name";
            // Birth Date
            dgv.Columns[7].Width = 170;
            dgv.Columns[7].HeaderText = "Birth Date";
            // Hire Date
            dgv.Columns[8].Width = 170;
            dgv.Columns[8].HeaderText = "Hire Date";
            // Address
            dgv.Columns[9].Width = 180;
            dgv.Columns[9].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgv.Columns[9].HeaderText = "Address";
            // Phone Number
            dgv.Columns[10].Width = 170;
            dgv.Columns[10].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgv.Columns[10].HeaderText = "Phone Number";
            // Email
            dgv.Columns[11].Width = 170;
            dgv.Columns[11].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgv.Columns[11].HeaderText = "Email";
            // Salary
            dgv.Columns[12].Width = 100;
            // Hide Job ID
            dgv.Columns[13].Visible = false;

            // Social Media
            dgv.Columns[14].Width = 150;
            dgv.Columns[15].Width = 150;
            dgv.Columns[16].Width = 150;
            dgv.Columns[17].Width = 150;
            dgv.Columns[18].Width = 150;
            dgv.Columns[18].HeaderText = "Google+";

            // Status
            dgv.Columns[19].Width = 90;

            // Hide Department ID Column
            dgv.Columns[20].Visible = false;

            // <- End Setup DataGridView ->

            NoTextBox.Focus();

            CreateAutoComplete();

        }

        private void CreateAutoComplete()
        {

            AutoCompleteStringCollection autoComp = new AutoCompleteStringCollection();
            foreach (DataRow row in this.employeeDatabaseDataSet.Tables["Employees"].Rows)
            {
                autoComp.Add((string)(row["First_Name"]) + ' ' + (string)(row["Last_Name"]));
            }

            toolStripTextBoxQuery.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            toolStripTextBoxQuery.AutoCompleteSource = AutoCompleteSource.CustomSource;
            toolStripTextBoxQuery.AutoCompleteCustomSource = autoComp;

        }


        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.employeesBindingSource.Filter = null;

            switch (toolStripComboBox1.SelectedIndex)
            {
                case 0:
                    this.employeesTableAdapter.FillTop10(this.employeeDatabaseDataSet.Employees);
                    break;
                case 1:
                    this.employeesTableAdapter.FillTop20(this.employeeDatabaseDataSet.Employees);
                    break;
                case 2:
                    this.employeesTableAdapter.FillTop30(this.employeeDatabaseDataSet.Employees);
                    break;
                case 3:
                    this.employeesTableAdapter.FillTop40(this.employeeDatabaseDataSet.Employees);
                    break;
                case 4:
                    this.employeesTableAdapter.FillTop50(this.employeeDatabaseDataSet.Employees);
                    break;
                case 5:
                    this.employeesTableAdapter.Fill(this.employeeDatabaseDataSet.Employees);
                    break;
                default:
                    break;
            }

        }

        private void refreshDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.employeesBindingSource.Filter = null;
                this.employeesTableAdapter.Fill(this.employeeDatabaseDataSet.Employees);
            }
            catch
            {
                // Something went wrong.
            }
        }

        private void PreviousButton_Click(object sender, EventArgs e)
        {
            this.employeesBindingSource.MovePrevious();
        }

        private void FirstButton_Click(object sender, EventArgs e)
        {
            this.employeesBindingSource.MoveFirst();
        }

        private void NextButton_Click(object sender, EventArgs e)
        {
            this.employeesBindingSource.MoveNext();
        }

        private void LastButton_Click(object sender, EventArgs e)
        {
            this.employeesBindingSource.MoveLast();
        }

        private void EnableEditingCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            this.enableEditingToolStripMenuItem.Checked = this.EnableEditingCheckBox.Checked;
        }

        private void enableEditingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //
        }

        private void enableEditingToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            this.EnableEditingCheckBox.Checked = this.enableEditingToolStripMenuItem.Checked;
        }

        private void deleteRecordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Backup your database first!

            if (this.EnableEditingCheckBox.Checked == true)
            {
                if (this.AddNewButton.Text == "Cancel")
                {
                    // Exit Sub
                    return;
                }

                // Not Operator
                if(!(dataGridView1.Rows.Count == 0))
                {
                    try
                    {
                        DialogResult result = new DialogResult();
                        result = MessageBox.Show("Do you want to permanently delete the selected record?", "Deletion Confirmation : iBasskung Tutorial", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                        if (result == DialogResult.Yes)
                        {
                            this.employeesBindingSource.RemoveCurrent();
                            this.employeesBindingSource.EndEdit();
                            this.employeesTableAdapter.Update(this.employeeDatabaseDataSet.Employees);
                        }
                        else
                        {
                            return;
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Unable to delete data from the database." + Environment.NewLine + "--> " + ex.Message.ToString(), "Delete data failed : iBasskung Tutorial", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }

            }
            else
            {
                MessageBox.Show("Access Denied!" + Environment.NewLine + "You need permission to perform this action." + Environment.NewLine + Environment.NewLine + "Problem Solution:" + Environment.NewLine + "Please contact the programmer or ask Google :)", "Delete operation failed : iBasskung Tutorial", MessageBoxButtons.OK, MessageBoxIcon.Stop);

                return;
            }

        }

        private void AddNewButton_Click(object sender, EventArgs e)
        {
            if(this.EnableEditingCheckBox.Checked == true)
            {

                this.employeesBindingSource.Filter = null;
                this.employeesTableAdapter.Fill(this.employeeDatabaseDataSet.Employees);

                int iYear = DateTime.Now.Year;
                int iMonth = DateTime.Now.Month;
                int iDay = DateTime.Now.Day;

                string formatDate = $"{iYear}{iMonth.ToString("00")}{iDay.ToString("00")}";

                this.FirstNameTextBox.Focus();

                if(this.AddNewButton.Text == "Add New")
                {
                    this.employeesBindingSource.AddNew();

                    this.EmployeeIDTextBox.Text = "IBK-" + formatDate + "-" + string.Format("{0:D5}", this.dataGridView1.Rows.Count - 1 + 1);

                    this.AddNewButton.Text = "Cancel";

                    this.PrefixComboBox.SelectedIndex = 0;
                    this.JobTitleComboBox.SelectedIndex = 0;
                    this.DepartmentComboBox.SelectedIndex = 0;
                }
                else
                {
                    this.employeesBindingSource.EndEdit();
                    this.AddNewButton.Text = "Add New";
                    this.employeesTableAdapter.Fill(this.employeeDatabaseDataSet.Employees);
                    return;
                }

            }
        }

        private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.AddNewButton.PerformClick();
        }

        private void EmployeeIDTextBox_TextChanged(object sender, EventArgs e)
        {
            // Not operator
            if (!string.IsNullOrEmpty(this.EmployeeIDTextBox.Text.ToString()))
            {
                string myNumber = this.EmployeeIDTextBox.Text.ToString().Substring(this.EmployeeIDTextBox.Text.ToString().Length - 5);

                long i64;
                if(long.TryParse(myNumber, out i64))
                {
                    this.NoTextBox.Text = i64.ToString();
                }else
                {
                    this.NoTextBox.Text = string.Empty;
                }
            }
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if(this.EnableEditingCheckBox.Checked == true)
            {

                try
                {

                    DialogResult result = new DialogResult();
                    result = MessageBox.Show("Do you want to save the selected record?", "Save | Update : iBasskung Tutorial", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if(result == DialogResult.Yes)
                    {

                        this.Validate();
                        this.employeesBindingSource.EndEdit();
                        this.employeesTableAdapter.Update(this.employeeDatabaseDataSet.Employees);

                        MessageBox.Show("Record has been saved successfully.", "Save Data : iBasskung Tutorial", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // refresh data :)
                        this.employeesTableAdapter.Fill(this.employeeDatabaseDataSet.Employees);

                        this.AddNewButton.Text = "Add New";

                        if(this.toolStripComboBox1.Items.Count > 0)
                        {
                            int idx = this.toolStripComboBox1.Items.Count - 1;
                            this.toolStripComboBox1.SelectedIndex = idx;
                        }
                        // so far :)
                    }
                    else
                    {
                        // do nothing :)
                        return;
                    }


                }
                catch(Exception ex)
                {
                    // Something went wrong.
                    MessageBox.Show("Unable to save data into the database." + Environment.NewLine + "--> " + ex.Message.ToString(), "Failed to save the data : iBasskung Tutorial", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }

            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SaveButton.PerformClick();
        }

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

        private void searchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if ((searchToolStripMenuItem.Text == "Search >>") && (toolStripTextBoxQuery.Visible == false))
            {
                ToolStripTextBox t = toolStripTextBoxQuery;
                t.Visible = true;
                t.Text = string.Empty;
                t.Focus();
                t.Select();

                searchToolStripMenuItem.Text = "Search <<";
                searchToolStripMenuItem.ForeColor = Color.Crimson;

                return;

            }
            else if ((toolStripTextBoxQuery.Visible == true) && (string.IsNullOrEmpty(toolStripTextBoxQuery.Text)))
            {
                toolStripTextBoxQuery.Visible = false;
                searchToolStripMenuItem.Text = "Search >>";
                searchToolStripMenuItem.ForeColor = Color.Black;
                             
                // one time refresh is enough :)
                oneTimeRefresh++;

                if (oneTimeRefresh > 1) return;

                // Refresh data
                this.employeesTableAdapter.FillByMyQueries(this.employeeDatabaseDataSet.Employees, null, null, null);
             
                return;
            }
            else
            {
                // Reset counter
                oneTimeRefresh = 0;

                string stringQuery = this.toolStripTextBoxQuery.Text.Trim().ToString();
                this.employeesTableAdapter.FillByFullNameAndAddress(this.employeeDatabaseDataSet.Employees, stringQuery, stringQuery, stringQuery, stringQuery);

                toolStripTextBoxQuery.Focus();
                toolStripTextBoxQuery.SelectAll();
            }
        }
    }

}

📝 Follow me around
Want to get updates on new courses or other cool free stuff? Just follow me on social media if that's your thing!

Twitter


Facebook āē _āē 

Facebook (✪ω✪)

Facebook ā° _ā° 

Google+


YouTube Channel

Dailymotion Channel

Free Source Code can be found here:

Thank you very much.

#VBNet #VisualBasic .Net #Programming #CodeAMinute #iBasskungTutorial #Udemy #OnlineCourses #SourceCode 

Comments