Accounting Project Part 6 Expenses Category Forms in C#

Hi, Dear's here we learn how to implement stock in Accounting Project  POS in Visual Studio using C#. Ilyasoft software company provide full project step by step training on our YouTube Channel ilyasoft software company so now subscribe, share and like.

In this tutorial we will cover all the below mention topics:
    i)      How to Create ExpensesForms Folder's inside Forms Folder in visual studio?
    ii)     How to Create Expenses Category Forms inside ExpensesForms  folder in our project?
    iii)    How to design Expenses category form?
    iv)    How to Insert, update, delete and retrieve records from expcategorytable and show inside datagridview?

So if you want all question answers watch the video, and for source code scroll down.


Design Expenses Category Form in C# / C-Sharp :
So in this example, we have category form, show below in figure:

Source Code Expenses Category Form : 
using System;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace POSAccounts.Forms.ExpensesForms
{
    public partial class FrmExpensesCategory : Form
    {
        public FrmExpensesCategory()
        {
            InitializeComponent();
            PanelBar.MouseDown += PanelBar_MouseDown;
        }

        private const int HT_CAPTION = 0x2; // what does this means
        private const int WM_NCLBUTTONDOWN = 0x00A1; // what does this means
        [DllImport("user32", CharSet = CharSet.Auto)]// what does this means
        private static extern bool ReleaseCapture();
        [DllImport("user32", CharSet = CharSet.Auto)]// what does this means
        private static extern int SendMessage(
        IntPtr hwnd,
        int wMsg,
        int wParam,
        int lParam);
        private void PanelBar_MouseDown(object sender, MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (e.Button == MouseButtons.Left)
            {
                Rectangle rct = DisplayRectangle;
                if (rct.Contains(e.Location))
                {
                    ReleaseCapture();
                    SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
                }
            }
        }
        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            FillGrid(txtSearch.Text.Trim());
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close(); // using to close current form
        }

        private void btnMinimize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }

        // Retrive Data From Category Table using Select Method of Database layer
        private void FillGrid(string searchvalue)
        {
            try
            {
                string query = "Select ExpCategoryID [ID], ExpCategoryName [Category] FROM ExpCategoryTable";
                if (!string.IsNullOrEmpty(searchvalue))
                {
                    query = "Select ExpCategoryID [ID], ExpCategoryName [Category] FROM ExpCategoryTable Where ExpCategoryName like '%" + searchvalue.Trim() + "%'";
                }

                DataTable dt = DatabaseLayer.Select(query);
                dgv.DataSource = dt;
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        dgv.Columns[0].Width = 80; // Category ID
                        dgv.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; // Exp Category Name
                    }
                }
            }
            catch
            {
                dgv.DataSource = null;
            }
        }

        // Validation Method for More Details Watch Vedio
        private void EnableComponents()
        {
            btnCancel.Visible = true;
            btnUpdate.Visible = true;
            btnSave.Visible = false;
            btnClear.Visible = false;
            dgv.Enabled = false;
            txtSearch.Enabled = false;
        }

        // Valition Method for More Details Watch Vedio
        private void ResetComponents()
        {
            btnCancel.Visible = false;
            btnUpdate.Visible = false;
            btnSave.Visible = true;
            btnClear.Visible = true;
            dgv.Enabled = true;
            txtSearch.Enabled = true;
            FillGrid(string.Empty);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            // Clear Category Name
            txtCategoryName.Clear();
        }

        private void FrmExpensesCategory_Load(object sender, EventArgs e)
        {
            // Load Registered Expenses Categories on form load
            FillGrid(string.Empty);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                ep.Clear();
                // First Check Category Textbox, if it's is empty then show message to user, plese enter category name
                if (txtCategoryName.Text.Trim().Length == 0)
                {
                    ep.SetError(txtCategoryName, "Please Enter Exp Category Title!");
                    txtCategoryName.Focus();
                    return;
                }

                // Check Category is already exist in table or not
                DataTable existdt = DatabaseLayer.Select("Select * From ExpCategoryTable Where  ExpCategoryName = '" + txtCategoryName.Text.Trim() + "'");
                if (existdt != null)
                {
                    if (existdt.Rows.Count > 0)
                    {
                        ep.SetError(txtCategoryName, "Already Exist!");
                        txtCategoryName.Focus();
                        txtCategoryName.SelectAll();
                        return;
                    }
                }

                // Now use database layer insert method to insert database in ExpCategoryTable.
                string insertquery = string.Format("Insert into ExpCategoryTable (ExpCategoryName) values('{0}')", txtCategoryName.Text.Trim());
                bool result = DatabaseLayer.Insert(insertquery); // user insert method for insert category in expcategorytable
                if (result == true)
                {
                    MessageBox.Show("Registered Successfully!"); // if Insert show success message
                    FillGrid(string.Empty);
                    txtCategoryName.Clear();
                }
            }
            catch
            {
                // incase of any issue is occure show this message
                MessageBox.Show("Some Unexptected issue is occure plz try agian!");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ResetComponents();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                ep.Clear();
                // First Check Category Textbox, if it's is empty then show message to user, plese enter category name
                if (txtCategoryName.Text.Trim().Length == 0)
                {
                    ep.SetError(txtCategoryName, "Please Enter Exp Category Title!");
                    txtCategoryName.Focus();
                    return;
                }

                // Check Category is already exist in table or not
                DataTable existdt = DatabaseLayer.Select("Select * From ExpCategoryTable Where  ExpCategoryName = '" + txtCategoryName.Text.Trim() + "' AND ExpCategoryID != '" + dgv.Rows[dgv.SelectedRows[0].Index].Cells[0].Value + "'");
                if (existdt != null)
                {
                    if (existdt.Rows.Count > 0)
                    {
                        ep.SetError(txtCategoryName, "Already Exist!"); // Show Existance Message near txtCategoryName
                        txtCategoryName.Focus();
                        txtCategoryName.SelectAll();
                        return;
                    }
                }

                // Now use database layer update method to update database in ExpCategoryTable.
                string updatequery = string.Format("Update ExpCategoryTable  set ExpCategoryName = '{0}' where ExpCategoryID = '{1}'", txtCategoryName.Text.Trim(), dgv.Rows[dgv.SelectedRows[0].Index].Cells[0].Value);
                bool result = DatabaseLayer.Update(updatequery);
                if (result == true)
                {
                    MessageBox.Show("Updated Successfully!"); // if update show success message
                    txtCategoryName.Clear();
                    ResetComponents();
                }
                else {
                    MessageBox.Show("Please Check in Try Again!"); // if not updated, show please proivde correct details
                }
            }
            catch
            {
                // incase of any issue is occure show this message
                MessageBox.Show("Some Unexptected issue is occure plz try agian!");
            }
        }
        // it's context menu strip edit tool click event, using to select record to edit 
        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgv != null)
            {
                if (dgv.Rows.Count > 0)
                {
                    if (dgv.SelectedRows.Count == 1)
                    {
                        if (MessageBox.Show("Are you sure you want to update selected Expenses Category?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            txtCategoryName.Text = dgv.Rows[dgv.SelectedRows[0].Index].Cells[1].Value.ToString();
                            EnableComponents();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please Select One Record!");
                    }
                }
            }
        }       
    }
}

Comments