C# Products Manager Project With MySQL Database

How To Make a C# Products Manager Project With MySQL Database Using Visual Studio

C# Products Manager Project With MySQL Database


In This C# Tutorial  We Will See How To Create a Simple Products Manager Project With Windows Form Using Csharp Programming Language And MySQL Database.

- Add a New Product.
- Edit Selected Product.
- Remove Selected Product.
- Display a List Of Products.
- Search For a  Product.
- Navigate Between Products.



Project 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;
using MySql.Data.MySqlClient;

namespace Products_Manager_App
{
    public partial class Management_Form : Form
    {
        public Management_Form()
        {
            InitializeComponent();
        }

        MySqlConnection connection = new MySqlConnection("datasource = localhost;port = 3306; initial catalog = csharp_products; username = root; password =");
        DataTable table = new DataTable();
        int productIndex = 0;

        // create a function to display products
        public void showProducts()
        {
            // clear the datatable first
            table.Clear();
            dataGridViewProducts.DataSource = table;

            MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM `product`", connection);
            adapter.Fill(table);
            dataGridViewProducts.DataSource = table;
            label_ProductsCount.Text = table.Rows.Count.ToString() + " Product";
        }
    
// the form load
        private void Management_Form_Load(object sender, EventArgs e)
        {
            // change DGV height
            dataGridViewProducts.RowTemplate.Height = 40;
            
            // display the close icon
            pictureBoxClose.Image = Properties.Resources.close;
            // display products on DGV
            showProducts();
            // select the first item in the combobox
            comboBoxCategories.SelectedIndex = 0;

            // customize DGV header
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(47,54,64);
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Verdana", 15, FontStyle.Italic);
            dataGridViewProducts.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewProducts.GridColor = Color.DarkBlue;
            dataGridViewProducts.AllowUserToAddRows = false;
            dataGridViewProducts.EnableHeadersVisualStyles = false;

        }
        
// picturebox to close the form and connection
        private void pictureBoxClose_Click(object sender, EventArgs e)
        {
            // close the connection
            if (ConnectionState.Open == connection.State)
            {
                connection.Close();
            }

            // close the app
            System.Environment.Exit(System.Environment.ExitCode);
        }

        // browse and display the image
        // + the image path
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            opf.Filter = "Choose Image(*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif";

            if(opf.ShowDialog() == DialogResult.OK)
            {
                pictureBoxProduct.Image = Image.FromFile(opf.FileName);
                textBoxImagePath.Text = opf.FileName;
            }
        }

// button insert a new product
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string name = textBoxName.Text;
                string category = comboBoxCategories.Text;
                int quantity = int.Parse(textBoxQuantity.Text);
                float price = float.Parse(textBoxPrice.Text);
                string imagePath = textBoxImagePath.Text;

                MySqlCommand command = new MySqlCommand("INSERT INTO `product`(`name`, `category`, `quantity`, `price`, `picture`) VALUES (@nm,@ctg,@qty,@prc,@pic)", connection);

                command.Parameters.Add("@nm", MySqlDbType.VarChar).Value = name;
                command.Parameters.Add("@ctg", MySqlDbType.VarChar).Value = category;
                command.Parameters.Add("@qty", MySqlDbType.Int16).Value = quantity;
                command.Parameters.Add("@prc", MySqlDbType.Float).Value = price;
                command.Parameters.Add("@pic", MySqlDbType.VarChar).Value = imagePath;

                if (ConnectionState.Closed == connection.State)
                {
                    connection.Open();
                }

                if (command.ExecuteNonQuery() == 1)
                {
                    showProducts();
                    MessageBox.Show("The Product Has Been Added Successfully", "Product Added", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("The Product Hasn't Been Added", "Product Not Added", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Enter The Product Info", "Empty Fileds", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        // display the selected product info
        private void dataGridViewProducts_Click(object sender, EventArgs e)
        {
            DataGridViewRow selectedRow = dataGridViewProducts.CurrentRow;

            numericUpDownID.Value = int.Parse(selectedRow.Cells[0].Value.ToString());
            textBoxName.Text = selectedRow.Cells[1].Value.ToString();
            comboBoxCategories.Text = selectedRow.Cells[2].Value.ToString();
            textBoxQuantity.Text = selectedRow.Cells[3].Value.ToString();
            textBoxPrice.Text = selectedRow.Cells[4].Value.ToString();
            textBoxImagePath.Text = selectedRow.Cells[5].Value.ToString();
            pictureBoxProduct.Image = Image.FromFile(selectedRow.Cells[5].Value.ToString());
        }

        // button update the selected product
        private void buttonEdit_Click(object sender, EventArgs e)
        {

            try
            {
                int id = (int)numericUpDownID.Value;
                string name = textBoxName.Text;
                string category = comboBoxCategories.Text;
                int quantity = int.Parse(textBoxQuantity.Text);
                float price = float.Parse(textBoxPrice.Text);
                string imagePath = textBoxImagePath.Text;

                MySqlCommand command = new MySqlCommand("UPDATE `product` SET `name`=@nm,`category`=@ctg,`quantity`=@qty,`price`=@prc,`picture`=@pic WHERE `id` = @id", connection);

                command.Parameters.Add("@nm", MySqlDbType.VarChar).Value = name;
                command.Parameters.Add("@ctg", MySqlDbType.VarChar).Value = category;
                command.Parameters.Add("@qty", MySqlDbType.Int16).Value = quantity;
                command.Parameters.Add("@prc", MySqlDbType.Float).Value = price;
                command.Parameters.Add("@pic", MySqlDbType.VarChar).Value = imagePath;
                command.Parameters.Add("@id", MySqlDbType.Int16).Value = id;

                if (ConnectionState.Closed == connection.State)
                {
                    connection.Open();
                }

                if (command.ExecuteNonQuery() == 1)
                {
                    showProducts();
                    MessageBox.Show("The Product Info Has Been Edited Successfully", "Edit Product", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("The Product Info Hasn't Been Edited", "Product Not Edited", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Enter The Product Info", "Empty Fileds", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }



        }

        // button search product by id
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            try
            {
                int id = (int)numericUpDownID.Value;
                DataRow[] row = table.Select("id = " + id);

                if(row.Length > 0)
                {
                    textBoxName.Text = row[0][1].ToString();
                    comboBoxCategories.Text = row[0][2].ToString();
                    textBoxQuantity.Text = row[0][3].ToString();
                    textBoxPrice.Text = row[0][4].ToString();
                    textBoxImagePath.Text = row[0][5].ToString();
                    pictureBoxProduct.Image = Image.FromFile(row[0][5].ToString());
                }
                else
                {
                    textBoxName.Text = "";
                    comboBoxCategories.SelectedIndex = 0;
                    textBoxQuantity.Text = "";
                    textBoxPrice.Text = "";
                    textBoxImagePath.Text = "";
                    pictureBoxProduct.Image = null;
                    MessageBox.Show("No Product With This ID, Enter a New One", "Product Not found", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show("Error -> " + ex.Message, "Product Not found", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            
        }

        // button remove product by id
        private void buttonRemove_Click(object sender, EventArgs e)
        {
            int id = (int)numericUpDownID.Value;

            MySqlCommand command = new MySqlCommand("DELETE FROM `product` WHERE `id` = @id", connection);

            command.Parameters.Add("@id", MySqlDbType.Int16).Value = id;

            if (ConnectionState.Closed == connection.State)
            {
                connection.Open();
            }

            if(MessageBox.Show("Are You Sure You Want To Remove This Product","Remove Product",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                if (command.ExecuteNonQuery() == 1)
                {
                    numericUpDownID.Value = 0;
                    textBoxName.Text = "";
                    comboBoxCategories.SelectedIndex = 0;
                    textBoxQuantity.Text = "";
                    textBoxPrice.Text = "";
                    textBoxImagePath.Text = "";
                    pictureBoxProduct.Image = null;
                    showProducts();
                    MessageBox.Show("Product Removed Successfully", "Remove Product", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Product NOT Removed", "Remove Product", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            

        }

        // button -> show the first item
        private void buttonFirst_Click(object sender, EventArgs e)
        {
            productIndex = 0;
            displayInfo(productIndex);
        }

        // button -> show the next item
        private void buttonNext_Click(object sender, EventArgs e)
        {
            productIndex ++;
            if (productIndex > table.Rows.Count - 1) { productIndex = table.Rows.Count - 1; }
            displayInfo(productIndex);
        }

        // button -> show the previous item
        private void buttonPrevious_Click(object sender, EventArgs e)
        {
            productIndex --;
            if (productIndex < 0) { productIndex = 0; }
            displayInfo(productIndex);
        }

        // button -> show the last item
        private void buttonLast_Click(object sender, EventArgs e)
        {
            productIndex = table.Rows.Count-1;
            displayInfo(productIndex);
        }

        // create a function to display info
        public void displayInfo(int index)
        {

            // select the DGV row
            dataGridViewProducts.ClearSelection();
            dataGridViewProducts.Rows[index].Selected = true; 

            numericUpDownID.Value = (int)table.Rows[index][0];
            textBoxName.Text = table.Rows[index][1].ToString();
            comboBoxCategories.Text = table.Rows[index][2].ToString();
            textBoxQuantity.Text = table.Rows[index][3].ToString();
            textBoxPrice.Text = table.Rows[index][4].ToString();
            textBoxImagePath.Text = table.Rows[index][5].ToString();
            pictureBoxProduct.Image = Image.FromFile(table.Rows[index][5].ToString());
        }

        // button to clear fields
        private void buttonClear_Click(object sender, EventArgs e)
        {
            numericUpDownID.Value = 0;
            textBoxName.Text = "";
            comboBoxCategories.SelectedIndex = 0;
            textBoxQuantity.Text = "";
            textBoxPrice.Text = "";
            textBoxImagePath.Text = "";
            pictureBoxProduct.Image = null;
        }

// allow only numbers in textboxquantity
        private void textBoxQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            // allow only numbers
            // you can use a numericupdown
            // or a maskedtextbox
            if(!Char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

// allow only float in textboxprice
        private void textBoxPrice_KeyUp(object sender, KeyEventArgs e)
        {
            // allow the user to enter values that can be converted to float
            // else remove the text

            try
            {
                float price = float.Parse(textBoxPrice.Text);
            }
            catch(Exception ex)
            {
                MessageBox.Show("Enter a Valid Price ( " + ex.Message + " )","Invalid Price",MessageBoxButtons.OK,MessageBoxIcon.Error);
                textBoxPrice.Text = "";
            }

        }

    }
}



      
///////////////OUTPUT:

C# Project With MySQL Database



if you want the source code click on the download button below











Share this

Related Posts

Previous
Next Post »