C SHARP AND MYSQL DATABASE CRUD TUTORIAL Insert Update Search Delete And Display Data On DataGridView Using Visual Studio 2010

C# (SHARP) AND MYSQL DATABASE CRUD TUTORIAL Insert Update Search Delete And Display Data On DataGridView Using Visual Studio 2010

This tutorial shows how to create crud(create, read, update, delete) application using c#(C-Sharp) programming language. In this tutorial i have shared screenshots and video tutorials that equips you with basics of c# windows forms application and Mysql database. In order to understand this tutorial you need to have c# and sql knowledge. You don’t need to be advanced programmer but basics will be enough to understand this guide. After going through this guide you will be able to perform almost all c# crud operations. This tutorial also contains code snippets for both c# and sql. Am programming in windows 7, using Microsoft visual studio 2010 integrated development environment (IDE) , xampp localhost( With Apache, MySQL, and PHP already configured). To connect to Mysql database am using MySql.Data.dll (MySql .NET Connector) which can be downloaded from Mysql official website. You will see how to add the connector in visual studio 2010 in this tutorial.

Table Of Contents

  1. How To Insert Update Search Delete And Display Data On DataGridView – Demo Video (Overview) – Project Walk-Through
  2. How To Create A New Form
  3. How To Display The Form At The Center Screen
  4. How To Add Panel To A Form
  5. How To Change Or Set Form Background Color
  6. How To Add Labels In A Form
  7. How To Add TextBoxes In A Form
  8. How To Add RadioButtons On A Form
  9. How To Add CheckBoxes On A Form
  10. How To Add Combobox On A Form
  11. How To Add Buttons On A Form
  12. How To Add Table On A Form
  13. How To Add Picturebox On A Form
  14. How To Add Image Icon On A Button
  15. How To Browse And Display Image On PictureBox
  16. How To Resize Image To Fit PictureBox
  17. How To Filter Image Types (Png, Jpg, Gif) (OpenFileDialog)
  18. How To Display Image Absolute Path (OpenFileDialog)
  19. How To Download Mysql Connector For Visual Studio C# Project
  20. How To Add Mysql Connector To Visual Studio 2010 Project
  21. How To Create New MySql Database Using PHPMyAdmin
  22. How To Connect To MySql Database – Part 1
  23. How To Connect To MySql Database – Part 2 .Net Framework 4.5.2 Download
  24. How To Connect To MySql Database – Part 3 Change The Target Framework
  25. How To Connect To MySql Database – Part 4 – Check Connection [XAMPP]
  26. How To Connect To MySql Database – Part 5 Opening Connection Function
  27. How To Connect To MySql Database – Part 6 Closing Connection Function
  28. How To Insert TextBox Text, Value, Data Into MySql Database – Part 1
  29. How To Insert TextBox Text, Value, Data Into MySql Database – Part 2
  30. How To Obtain Only The Filename (OpenFileDialog) Insert Into Db – Part 3
  31. How To Insert Radio Button Values, Data Into MySql Database
  32. How To Insert Checkbox Value, Data Into Database Using C#
  33. How To Insert Combobox Selected Item, Value Into Mysql In C#
  34. How To Save Or Insert Image Into Mysql Database In C#
  35. How To Retrieve Data From Mysql And Display It On DataGridView In C#
  36. How To Automatically Adjust Columns Width To Fit In The DataGridView In C#
  37. How To Increase (Change Or Set) DataGridView Row Height In C#
  38. How To Stretch An Image In C# DataGridView Fit Image In Column Row Cell
  39. How To Create Getter And Setter, Constructor In C# – Shortcut
  40. How To Read Mysql Data And Store Them In Array List C#
  41. How To Populate (Bind) Datagridview From List Of Items In C#
  42. How To Move a Line(Selected Code) Up or Down in Visual Studio
  43. How To Check If Datagridview Row Is Selected Or Not In C#
  44. How To Get Datagridview Currently Selected Row Index On Row click C#
  45. How To Display Selected Row From Datagridview To Textboxes In C#
  46. How To Display Selected Row Image From Datagridview To Picturebox C#
  47. How To Display Selected Row Value From Datagridview To RadioButton C#
  48. How To Display Selected Row Value From Datagridview To CheckBox C#
  49. How To Display Selected Row Value From Datagridview To ComboBox C#
  50. How To clear Or Reset a combobox On Button Click In C#
  51. How To clear Or Reset Radio Button On Button Click In C#
  52. How To clear Or Reset Check Box On Button Click In C#
  53. How To clear Or Reset Text Boxes On Button Click In C#
  54. How To clear Or Reset Image On A Picturebox On Button Click In C#
  55. How To Make Only One Checkbox Checked At A Time C#
  56. How To Disable Text Input [Editing] In TextBox In C#
  57. How To Check If Input Fields Are Empty In C#
  58. How To Delete Data From Table In MySql Using C#
  59. How To Refresh Datagridview Rows After Change In MySql C#
  60. How To Update Data From Table In MySql Using C#
  61. How To Search Data From MySql and Filter in datagridview Table In C#
  62. Fixing (GUI) Graphical User Interface
  63. Complete Video Tutorial

How To Insert Update Search Delete And Display Data On DataGridView – Demo Video (Overview) – Project Walk-Through

This is an overview showing complete project in action. In this video I am demonstrating how the application works.
To insert the data to Mysql database and display on DataGridView you need to start XAMPP Localhost. Xampp has Mysql where the data is stored. I am storing data (Text and images) in a single database. I have only one table created in the database. The table has different columns where different type of data is stored. ID column is the ‘Primary Key’ and auto-increments whenever you create or insert a new row. Images are stored in the database as Large BLOB(Binary Large OBject).

DEMO VIDEO

C# AND MYSQL DATABASE CRUD TUTORIAL #0 – How To Insert Update Search Delete And Display Data On DataGridView – Demo Video (Overview) – Project Walk-Through


How To Create A New Form

Start Visual Studio 2010.
Select the File menu, then New, then Project.

How To Create A New Form New Project
How To Create A New Form New Project

On the right pane choose/select windows forms application.
Name the project and the solution: CSHARPANDMYSQLDATABASECRUD
Browse to the place on your computer where you wish Visual Studio 2010
to create the directory for your solution (keeping the check box selected).
Click okay and you will be taken to a new forms window.

How To Create A New Form - New C SHarp Form Project
How To Create A New Form – New C SHarp Form Project

New form gets created immediately and you can resize it by increasing width and height. This can be done by dragging the edges or changing the forms properties.

How To Create A New Form - New Form
How To Create A New Form – New Form

Solution Explorer Shows the files created for your project.

How To Create A New Form - Solution Explorer
How To Create A New Form – Solution Explorer

In Solution Explorer, right click On Your Project Name And Select “Open Project In Windows Explorer”. This is only when you want to know the location where your c# project files are stored.

How To Create A New Form - Browse Folder Location
How To Create A New Form – Browse Folder Location

This is the location you chose when creating new project.

How To Create A New Form - Project Location
How To Create A New Form – Project Location

Form1.cs

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 CSHARPANDMYSQLDATABASE
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

Form1.Designer.cs

namespace CSHARPANDMYSQLDATABASE
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Text = "Form1";
        }

        #endregion
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace CSHARPANDMYSQLDATABASE
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #1 – How To Create A New Form


How To Display The Form At The Center Screen

By default the project might not start at the center of the screen, to start the window in the center screen, select it, then go to properties and set start position to center screen.

How To Display The Form At The Center Screen
How To Display The Form At The Center Screen

When you run the project it should start at the center of the screen.

How To Display The Form At The Center Screen Positioned
How To Display The Form At The Center Screen Positioned

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #2 – How To Display The Form At The Center Screen


How To Add Panel To A Form

Drag and drop panel from toolbox onto the form.

How To Add Panel To A Form
How To Add Panel To A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #3 – How To Add Panel To A Form


How To Change Or Set Form Background Color

Select the form, then go to properties and click next to “BackColor” and choose the desired color.

How To Change Or Set Form Background Color
How To Change Or Set Form Background Color

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #4 – How To Change Or Set Form Background Color


How To Add Labels In A Form

Drag and drop label from toolbox onto the form.

How To Add Labels In A Form
How To Add Labels In A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #5 – How To Add Labels In A Form


How To Add TextBoxes In A Form

Drag and drop TextBox from toolbox onto the form.

How To Add TextBoxes On A Form
How To Add TextBoxes On A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #6 – How To Add TextBoxes On A Form


How To Add RadioButtons On A Form

Drag and drop RadioButton from toolbox onto the form.

How To Add RadioButtons On A Form
How To Add RadioButtons On A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #7 – How To Add RadioButtons On A Form


How To Add CheckBoxes On A Form

Drag and drop CheckBox from toolbox onto the form.

How To Add CheckBoxes On A Form
How To Add CheckBoxes On A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #8 – How To Add CheckBoxes On A Form


How To Add Combobox On A Form

Drag and drop ComboBox from toolbox onto the form.

How To Add Combobox On A Form
How To Add Combobox On A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #9 – How To Add Combobox On A Form


How To Add Buttons On A Form

Drag and drop Button from toolbox onto the form.

How To Add Buttons On A Form
How To Add Buttons On A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #10 – How To Add Buttons On A Form


How To Add DataGridView (Table) On A Form

Drag and drop DataGridView from toolbox onto the form.

How To Add DataGridView On A Form
How To Add DataGridView On A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #11 – How To Add Table On A Form


How To Add Picturebox On A Form

Drag and drop PictureBox from toolbox onto the form.

How To Add Picturebox On A Form
How To Add Picturebox On A Form

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #12 – How To Add Picturebox On A Form


How To Add Image Icon On A Button

First you need to add image icons to your project resources folder.

Right Click On your project from solution explorer, and select properties.

How To Add Image Icon On A Button - Properties
How To Add Image Icon On A Button – Properties

Select resources tab.

Then from Add resource dropdown, Select Add Existing File.

How To Add Image Icon On A Button - Add Existing File
How To Add Image Icon On A Button – Add Existing File

Select icons from your computer and click open.

How To Add Image Icon On A Button - Select From PC
How To Add Image Icon On A Button – Select From PC

Select a button, then go to properties and click next to Image.

How To Add Image Icon On A Button
How To Add Image Icon On A Button

check “Project resource file” radio button and select an icon from the list. Then click Okay to add it on the button.

How To Add Image Icon On A Button - From Resources
How To Add Image Icon On A Button – From Resources

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #13 – How To Add Image Icon On A Button

How To Browse And Display Image On PictureBox

Browse button opens dialog box where you can choose image from your computer.

How To Browse And Display Image On PictureBox
How To Browse And Display Image On PictureBox

Choose one image from your PC and click open.

How To Browse And Display Image On PictureBox - Dialog Box
How To Browse And Display Image On PictureBox – Dialog Box

After you click open the image is displayed on picturebox.

How To Browse And Display Image On PictureBox - Image Selected
How To Browse And Display Image On PictureBox – Image Selected

C# SOURCE CODE

        //Browse image from the copmputer and display it on picturebox on button click.
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            //Filter Only Image with the following extensions.
            ofd.Filter = "Choose Only Images|*.png;*.jpg;*.gif;";
            //Dialog box title.
            ofd.Title = "Choose Image";
            //If Open Button from opened dialog box is Clicked.
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //Displaying image on picturebox.
                pictureBox1.Image = Image.FromFile(ofd.FileName);
                //Displaying image path On Disabled textbox.
                textBoxImagePath.Text = ofd.FileName;
                //Getting Image Filename
                textBoxImageName.Text = Path.GetFileName(ofd.FileName);
            }
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #14 – How To Browse And Display Image On PictureBox

How To Resize Image To Fit PictureBox

Click on picturebox to select it. Click on small right arrow icon located at the top right of the picturebox.

How To Resize Image To Fit PictureBox
How To Resize Image To Fit PictureBox

Change Size Mode To “StretchImage”.

How To Resize Image To Fit PictureBox - Stretched
How To Resize Image To Fit PictureBox – Stretched

C# SOURCE CODE

            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #15 – How To Resize Image To Fit PictureBox


How To Filter Image Types (Png, Jpg, Gif) (OpenFileDialog)

This Filters Only File of type png, jpg and gif.

C# SOURCE CODE

                       //Filter Only Image with the following extensions.
            ofd.Filter = "Choose Only Images|*.png;*.jpg;*.gif;";

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #16 – How To Filter Image Types (Png, Jpg, Gif)


How To Display Image Absolute Path (OpenFileDialog)

C# SOURCE CODE

                //Displaying image path On Disabled textbox.
                textBoxImagePath.Text = ofd.FileName;

Image path is displayed in disabled textbox.

How To Display Image Absolute Path OpenFileDialog
How To Display Image Absolute Path OpenFileDialog

C# SOURCE CODE

                //Displaying image path On Disabled textbox.
                textBoxImagePath.Text = ofd.FileName;

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #17 – How To Display Image Absolute Path (OpenFileDialog)

How To Download Mysql Connector For Visual Studio C# Project

Step 1. Go to https://dev.mysql.com/downloads/connector/net/

Select “.NET & Mono” from the dropdown list. Then Click Download Button Next to Zip File.

How To Download Mysql Connector NET For Visual Studio C# Project
How To Download Mysql Connector NET For Visual Studio C# Project

Step 2 – Click “No Thanks, Just Start My Download”.

How To Download Mysql Connector NET For Visual Studio C# Project Zip
How To Download Mysql Connector NET For Visual Studio C# Project Zip

Step 3 – Click Open To Open mysql connector/NET automatically with winrar when the download completes.

 How To Download Mysql Connector NET For Visual Studio C# Project Zip Download
How To Download Mysql Connector NET For Visual Studio C# Project Zip Download

Step 4 – Wait For The Download To Finish.

You can view the download progress by clicking the down arrow as shown in the screenshot below. Am Using Mozilla FireFox Browser.

How To Download Mysql Connector NET For Visual Studio C# Project - Downloading
How To Download Mysql Connector NET For Visual Studio C# Project – Downloading

Step 5 – When the download finishes, Zip file Opens Automatically In Winrar. This is because I chose that option before the download started.

How To Download Mysql Connector NET For Visual Studio C# Project - Download Complete
How To Download Mysql Connector NET For Visual Studio C# Project – Download Complete

Step 6 – Open any folder to check the files inside.

How To Download Mysql Connector NET For Visual Studio C# Project - File In Winrar
How To Download Mysql Connector NET For Visual Studio C# Project – File In Winrar

Step 7 – Select The Downloaded Zip file.

How To Download Mysql Connector NET For Visual Studio C# Project - Temp Folder
How To Download Mysql Connector NET For Visual Studio C# Project – Temp Folder

Step 8 – Right Click And Select Extract To A Folder.

How To Download Mysql Connector NET For Visual Studio C# Project - Extract To A Folder Inside Temp
How To Download Mysql Connector NET For Visual Studio C# Project – Extract To A Folder Inside Temp

Step 9 – The files are extracted to specified folder.

How To Download Mysql Connector NET For Visual Studio C# Project - Extracted To A Folder
How To Download Mysql Connector NET For Visual Studio C# Project – Extracted To A Folder

Step 10 – If you extracted the files in temp folder, copy them to another location because this is a temporary folder. Anything stored here gets deleted in case you wipe your PC. (With software like CCleaner).

How To Download Mysql Connector NET For Visual Studio C# Project - Copy Folder To Desired Location
How To Download Mysql Connector NET For Visual Studio C# Project – Copy Folder To Desired Location

Step 11 – Open the Folder where the files are stored.

How To Download Mysql Connector NET For Visual Studio C# Project - Open Folder From Desktop
How To Download Mysql Connector NET For Visual Studio C# Project – Open Folder From Desktop

Step 12 – Here you can see mysql.data.dll file. This is the file you add to your integrated development environment (IDE) like Visual Studio 2010.

How To Download Mysql Connector NET For Visual Studio C# Project - NET Connector File
How To Download Mysql Connector NET For Visual Studio C# Project – NET Connector File

VIDEO TUTORIAL

How To Download Mysql Connector/NET For Visual Studio C# Project


How To Add Mysql Connector To Visual Studio 2010 Project

Right Click on project name from solution explorer.

Select add reference.

How To Display Image Absolute Path OpenFileDialog - Right Click Then Add Reference
How To Display Image Absolute Path OpenFileDialog – Right Click Then Add Reference

click on browse tab.

Locate the connector folder and open it.

Select MySql.Data.Dll.

Click Ok.

How To Display Image Absolute Path OpenFileDialog - Browse Mysql Connector File
How To Display Image Absolute Path OpenFileDialog – Browse Mysql Connector File

Mysql.Data is added to references section.

This means mysql connector/NET has been added in your project successfully.

How To Display Image Absolute Path OpenFileDialog - Added To Reference
How To Display Image Absolute Path OpenFileDialog – Added To Reference

This is the folder where MySql Connector/NET is found.

How To Add Mysql Connector To Visual Studio 2010 Project - Connector Folder
How To Add Mysql Connector To Visual Studio 2010 Project – Connector Folder

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #18 – How To Add Mysql Connector To Visual Studio


How To Create New MySql Database Using PHPMyAdmin

Start xampp control panel.

If you have shortcut click it to start xampp.

If you don’t, Start xampp from installation location.

How To Create New MySql Database Using PHPMyAdmin - Xampp Location
How To Create New MySql Database Using PHPMyAdmin – Xampp Location

Start both Apache and Mysql.

How To Create New MySql Database Using PHPMyAdmin - Start Xampp
How To Create New MySql Database Using PHPMyAdmin – Start Xampp

Both services are now running.

How To Create New MySql Database Using PHPMyAdmin - Start apache and mysql
How To Create New MySql Database Using PHPMyAdmin – Start apache and mysql

Click Admin next to mysql to stat PHPMyadmin GUI. On your browser.

How To Create New MySql Database Using PHPMyAdmin - Admin Next To mysql
How To Create New MySql Database Using PHPMyAdmin – Admin Next To mysql

Click New To create new database.

How To Create New MySql Database Using PHPMyAdmin  - phpmyadmin Homepage
How To Create New MySql Database Using PHPMyAdmin – phpmyadmin Homepage

Enter database name and click create button.

How To Create New MySql Database Using PHPMyAdmin - Enter Database Name
How To Create New MySql Database Using PHPMyAdmin – Enter Database Name

The database is created without any table inside.

How To Create New MySql Database Using PHPMyAdmin - Database Created
How To Create New MySql Database Using PHPMyAdmin – Database Created

On the left pane under created database, click on new, to create new table.

Enter table name and add required columns and their datatypes.

How To Create New MySql Database Using PHPMyAdmin - Create New Table
How To Create New MySql Database Using PHPMyAdmin – Create New Table

To check the table structure click on structure tab.

How To Create New MySql Database Using PHPMyAdmin - Table Structure
How To Create New MySql Database Using PHPMyAdmin – Table Structure

To run a query for selecting all data from the table click on “SQL” tab.

Enter query in the text area.

How To Create New MySql Database Using PHPMyAdmin - Select All
How To Create New MySql Database Using PHPMyAdmin – Select All

Click “GO” to run your query.

How To Create New MySql Database Using PHPMyAdmin - All Table Data Selected
How To Create New MySql Database Using PHPMyAdmin – All Table Data Selected

SQL QUERY

-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 20, 2020 at 02:46 PM
-- Server version: 10.3.15-MariaDB
-- PHP Version: 7.3.6

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `csharpandmysqlcrudinsertupdatedeleteselect`
--
CREATE DATABASE IF NOT EXISTS `csharpandmysqlcrudinsertupdatedeleteselect` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `csharpandmysqlcrudinsertupdatedeleteselect`;

-- --------------------------------------------------------

--
-- Table structure for table `csharpandmysqlcrudinsertupdatedeleteselecttable`
--

DROP TABLE IF EXISTS `csharpandmysqlcrudinsertupdatedeleteselecttable`;
CREATE TABLE IF NOT EXISTS `csharpandmysqlcrudinsertupdatedeleteselecttable` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `FirstName` varchar(50) NOT NULL,
  `LastName` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `Gender` varchar(20) NOT NULL,
  `Language` varchar(50) NOT NULL,
  `Country` varchar(50) NOT NULL,
  `ImageName` varchar(50) NOT NULL,
  `ImagePath` varchar(255) NOT NULL,
  `ImageBlob` longblob NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `csharpandmysqlcrudinsertupdatedeleteselecttable`
--

COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #19 – How To Create New MySql Database – PHPMyAdmin


How To Connect To MySql Database – Part 1

To work with database you need to be connected.

MySQLDatabaseConnection.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using System.Windows.Forms;

namespace JAVAANDMYSQLDATABASECRUD
{
    public class MySQLDatabaseConnection
    {
        MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=csharpandmysqlcrudinsertupdatedeleteselect");

        //Function to get connection

        public MySqlConnection getDatabaseConnection()
        {
            return connection;
        }

        //Open Connection function

        public void openDBConnection() {
            //Check if Connection Is Closed And Open It
            if (connection.State == ConnectionState.Closed)
            {
                //MessageBox.Show("Connection Opened");
                connection.Open();
            }
        }

        //Close Connection function

        public void closeDBConnection()
        {
            //Check if Connection Is Open And Close It
            if (connection.State == ConnectionState.Open)
            {
                //MessageBox.Show("Connection Closed");
                connection.Close();
            }
        }
        
    }
}

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #20 – How To Connect To MySql Database – Part 1


How To Connect To MySql Database – Part 2 .Net Framework 4.5.2 Download

To download .Net Framework 4.5.2 go to https://www.microsoft.com/en-us/download/details.aspx?id=42642

Click Download button to begin the download process.

How To Download And Install Net Framework 4 5 2 - Official Microsoft Website
How To Download And Install Net Framework 4 5 2 – Official Microsoft Website

When the download finishes, run the downloaded file and follow all the steps till .Net Framework 4.5.2 is completely installed.

How To Download And Install Net Framework 4 5 2 - Downloaded and installed
How To Download And Install Net Framework 4 5 2 – Downloaded and installed

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #21 – How To Connect To MySql Database – Part 2 .Net Framework 4.5.2 Download


How To Connect To MySql Database – Part 3 Change The Target Framework

I had to change the configuration xml file targeted framework to 4.5.2 from 4.0 because i was getting this error “The primary reference “MySql.Data” could not be resolved because it was built against the “.NETFramework,Version=v4.5” framework. This is a higher version than the currently targeted framework “.NETFramework,Version=v4.0”.”.

How To Change The Target Framework In Visual Studio 2010 by updating the .csproj Xml File

This solution fixes the above error.

I have .NETFramework Version=v4.5.2 already installed in windows 7. Am going to point my project to this version in my settings.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - FW 452
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – FW 452

To Check currently selected framework version right click on your project then select properties.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Properties
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Properties

Click on application tab and check the target framework. You can choose different framework from the drop down list.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Target Framework
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Target Framework

Right click on your project and select “Unload Project”.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Unloading project
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Unloading project

Right click on unloaded project and select edit (ProjectName) .csproj.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Edit .csproj
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Edit .csproj

Change The following sections to targeted framework version.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Before Changing FW
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Before Changing FW

In this case am targeting .NET Framework version 4.5.2

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - XML File
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – XML File

Save your settings then right click on project name and select “Reload Project”.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Reload Project
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Reload Project

Click Okay When you are prompted to close open document.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Close Open Doc
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Close Open Doc

Project is reloaded, And it’s available in solution explorer.

How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File - Project Reloaded
How To Change The Target Framework In Visual Studio 2010 by updating the dot csproj Xml File – Project Reloaded

Try to run your project again and it should run without any problem.

.CSPROJ XML FILE AFTER RECTIFYING THE ERROR.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.5.2" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>8.0.30703</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{8C91C6DC-A0DD-4EA2-AA0E-5C49F949BC67}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>JAVAANDMYSQLDATABASECRUD</RootNamespace>
    <AssemblyName>JAVAANDMYSQLDATABASECRUD</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <TargetFrameworkProfile>
    </TargetFrameworkProfile>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <Prefer32Bit>false</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <Prefer32Bit>false</Prefer32Bit>
  </PropertyGroup>
  <PropertyGroup>
    <StartupObject>
    </StartupObject>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="MySql.Data, Version=8.0.17.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\..\Downloads\mysql-connector-net-8.0.17-noinstall (1)\v4.5.2\MySql.Data.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Deployment" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
    <Compile Include="MySQLDatabaseConnection.cs" />
    <Compile Include="Person.cs" />
    <Compile Include="PersonData.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <EmbeddedResource Include="Form1.resx">
      <DependentUpon>Form1.cs</DependentUpon>
    </EmbeddedResource>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
      <SubType>Designer</SubType>
    </EmbeddedResource>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Resources.resx</DependentUpon>
      <DesignTime>True</DesignTime>
    </Compile>
    <None Include="app.config" />
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
    </Compile>
  </ItemGroup>
  <ItemGroup>
    <None Include="Resources\x-button.png" />
  </ItemGroup>
  <ItemGroup>
    <None Include="Resources\plus-1.png" />
  </ItemGroup>
  <ItemGroup>
    <None Include="Resources\refresh-24.png" />
  </ItemGroup>
  <ItemGroup>
    <None Include="Resources\x-button1.png" />
  </ItemGroup>
  <ItemGroup>
    <None Include="Resources\clear.png" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #22 – How To Connect To MySql Database – Part 3 Changing The Target Framework


How To Connect To MySql Database – Part 4 – Check Connection [XAMPP]

Check if database connection is established.

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #23 – How To Connect To MySql Database – Part 4 – Check Connection [XAMPP]


How To Connect To MySql Database – Part 5 Opening Connection Function

To work on database you need to open database connection.

C# SOURCE CODE

        //Open Connection function

        public void openDBConnection() {
            //Check if Connection Is Closed And Open It
            if (connection.State == ConnectionState.Closed)
            {
                //MessageBox.Show("Connection Opened");
                connection.Open();
            }
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #24 – How To Connect To MySql Database – Part 5 Opening Connection Function


How To Connect To MySql Database – Part 6 Closing Connection Function

It’s a good practice to close database connection after running queries.

C# SOURCE CODE

        //Close Connection function

        public void closeDBConnection()
        {
            //Check if Connection Is Open And Close It
            if (connection.State == ConnectionState.Open)
            {
                //MessageBox.Show("Connection Closed");
                connection.Close();
            }
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #25 – How To Connect To MySql Database – Part 6 Closing Connection Function


How To Insert TextBox Text, Value, Data Into MySql Database – Part 1

The values from textboxes are inserted to database varchar columns.

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #26 – How To Insert TextBox Text Or Value Or Data Into MySql Database – Part 1


How To Insert TextBox Text, Value, Data Into MySql Database – Part 2

How To Insert TextBox Text Value Data Into MySql Database
How To Insert TextBox Text Value Data Into MySql Database

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #26 – How To Insert TextBox Text Or Value Or Data Into MySql Database – Part 1


How To Obtain Only The Filename (OpenFileDialog) Insert Into Db – Part 3

This is extracting the file name from the full path.

C# SOURCE CODE

                //Getting Image Filename
                textBoxImageName.Text = Path.GetFileName(ofd.FileName);

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #28 – How To Obtain Only The Filename (OpenFileDialog) Insert Into Db – Part 3


How To Insert Radio Button Values, Data Into MySql Database

Radio button values are inserted to database as varchar.

How To Insert Radio Button Values Data Into MySql Database
How To Insert Radio Button Values Data Into MySql Database

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #29 – How To Insert Radio Button Values Or Data Into Mysql Database


How To Insert Checkbox Value, Data Into Database Using C#

CheckBox values are saved in tables varchar column.

How To Insert Checkbox Value Data Into Database Using C
How To Insert Checkbox Value Data Into Database Using C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #30 – How To Insert Checkbox Values Or Data Into Database


How To Insert Combobox Selected Item, Value Into Mysql In C#

Selected value from dropdown is inserted to tables varchar column.

How To Insert Combobox Selected Item Value Into Mysql In C
How To Insert Combobox Selected Item Value Into Mysql In C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #31 – How To Insert Combobox Selected Item Or Value Into Mysql Database


How To Save Or Insert Image Into Mysql Database In C#

Image from picturebox is inserted to large BLOB column.

How To Save Or Insert Image Into Mysql Database
How To Save Or Insert Image Into Mysql Database

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #32 – How To Save Or Insert Image Into Mysql Database


How To Retrieve Data From Mysql And Display It On DataGridView In C#

All rows are displayed In DataGridView from Mysql table when you run the application. Also the datagridview refreshes when you : insert new row(data), delete a row, update a row etc…..

Person.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JAVAANDMYSQLDATABASECRUD
{
    class Person
    {
        //Shortcut For Creating properties and getters and setters
        // Type propfull and double click Tab

        private int _Id;
        private string _FirstName;
        private string _LastName;
        private string _Email;
        private string _Gender;
        private string _Language;
        private string _Country;
        private string _ImageName;
        private string _ImagePath;
        private byte[] _ImageBlob;


        //To create Constructor Type ctor, then tab key twice
        public Person()
        {

        }

        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }
        
        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }

        public string LastName
        {
            get { return _LastName; }
            set { _LastName = value; }
        }

        public string Email
        {
            get { return _Email; }
            set { _Email = value; }
        }

        public string Gender
        {
            get { return _Gender; }
            set { _Gender = value; }
        }

        public string Language
        {
            get { return _Language; }
            set { _Language = value; }
        }

        public string Country
        {
            get { return _Country; }
            set { _Country = value; }
        }

        public string ImageName
        {
            get { return _ImageName; }
            set { _ImageName = value; }
        }        

        public string ImagePath
        {
            get { return _ImagePath; }
            set { _ImagePath = value; }
        }

        public byte[] ImageBlob
        {
            get { return _ImageBlob; }
            set { _ImageBlob = value; }
        }


    }
}

PersonData.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace JAVAANDMYSQLDATABASECRUD
{
    class PersonData
    {
        MySQLDatabaseConnection dbCONN = new MySQLDatabaseConnection();
        public List<Person> PersonList(string valueToSearch)
        {

            List<Person> personList = new List<Person>();
            String selectFromMysqlDatabase = "SELECT * FROM `csharpandmysqlcrudinsertupdatedeleteselecttable` WHERE CONCAT_WS(' ', `Id`, `FirstName`, `LastName`, `Email`, `Gender`, `Language`, `Country`, `ImageName`, `ImagePath`, `ImageBlob`) LIKE '%"+ valueToSearch+"%' ";
            MySqlCommand command;
            MySqlDataReader reader;
            Person person;

            dbCONN.openDBConnection();
            try
            {
                command = new MySqlCommand(selectFromMysqlDatabase, dbCONN.getDatabaseConnection());
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    person = new Person();
                    person.Id = Convert.ToInt32(reader[0].ToString());
                        //.GetInt32(reader[0].ToString());
                    person.FirstName = reader[1].ToString();
                    person.LastName = reader[2].ToString();
                    person.Email = reader[3].ToString();
                    person.Gender = reader[4].ToString();
                    person.Language = reader[5].ToString();
                    person.Country = reader[6].ToString();
                    person.ImageName = reader[7].ToString();
                    person.ImagePath = reader[8].ToString();
                    person.ImageBlob = (byte[])reader[9];

                    personList.Add(person);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("Error " + err.StackTrace);
            }
            finally
            {
                //reader.Close();
                //command.Dispose();
                dbCONN.closeDBConnection();

            }

            return personList;

        }
    }
}

C# SOURCE CODE

        private void Form1_Load(object sender, EventArgs e)
        {
            //Fill Datagridview with data from mysql database when form loads 
            refreshDatagridView("");

        }

        private void refreshDatagridView(string searchValue)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.RowTemplate.Height = 45;

            BindingSource bsource = new BindingSource();
            PersonData pData = new PersonData();
            bsource.DataSource = pData.PersonList(searchValue);
            dataGridView1.DataSource = bsource;

            //Fit Image In DataGridView Cell
            DataGridViewImageColumn dGVimageColumn = (DataGridViewImageColumn)dataGridView1.Columns[9];
            dGVimageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;
        }
How To Retrieve Data From Mysql And Display It On DataGridView In C
How To Retrieve Data From Mysql And Display It On DataGridView In C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #33 – How To Retrieve Data From Mysql And Display It On DataGridView


How To Automatically Adjust Columns Width To Fit In The DataGridView In C#

This makes the column fit to the datagridview. Sometimes columns might be less than the datagridview size. This Enable them To adjust automatically to fill datagridview.

Automatically Adjust Columns Width To Fit In The DataGridView  In C
Automatically Adjust Columns Width To Fit In The DataGridView In C

C# SOURCE CODE

            this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #34 – How To Automatically Adjust Columns Width To Fit In The DataGridView


How To Increase (Change Or Set) DataGridView Row Height In C#

It is important to increase or decrease the row height for clear view of the cell content.

C# SOURCE CODE

            dataGridView1.RowTemplate.Height = 45;

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #35 – How To Increase (Change Or Set) DataGridView Row Height


How To Stretch An Image In C# DataGridView Fit Image In Column Row Cell

Images should be visible in full format. This is done by stretching them to fit the cell.

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #36 – How To Stretch An Image to Fit In DataGridView Cell


How To Create Getter And Setter, Constructor In C# – Shortcut

Getters, setters and constructors simplify the whole coding process and reduce the code.

C# SOURCE CODE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JAVAANDMYSQLDATABASECRUD
{
    class Person
    {
        //Shortcut For Creating properties and getters and setters
        // Type propfull and double click Tab

        private int _Id;
        private string _FirstName;
        private string _LastName;
        private string _Email;
        private string _Gender;
        private string _Language;
        private string _Country;
        private string _ImageName;
        private string _ImagePath;
        private byte[] _ImageBlob;


        //To create Constructor Type ctor, then tab key twice
        public Person()
        {

        }

        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }
        
        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }

        public string LastName
        {
            get { return _LastName; }
            set { _LastName = value; }
        }

        public string Email
        {
            get { return _Email; }
            set { _Email = value; }
        }

        public string Gender
        {
            get { return _Gender; }
            set { _Gender = value; }
        }

        public string Language
        {
            get { return _Language; }
            set { _Language = value; }
        }

        public string Country
        {
            get { return _Country; }
            set { _Country = value; }
        }

        public string ImageName
        {
            get { return _ImageName; }
            set { _ImageName = value; }
        }        

        public string ImagePath
        {
            get { return _ImagePath; }
            set { _ImagePath = value; }
        }

        public byte[] ImageBlob
        {
            get { return _ImageBlob; }
            set { _ImageBlob = value; }
        }


    }
}

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #37 – How To Create Getters Setters And Constructor – Shortcut


How To Read Mysql Data And Store Them In Array List C#

All rows from mysql database are stored in an arraylist function.

C# SOURCE CODE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace JAVAANDMYSQLDATABASECRUD
{
    class PersonData
    {
        MySQLDatabaseConnection dbCONN = new MySQLDatabaseConnection();
        public List<Person> PersonList(string valueToSearch)
        {

            List<Person> personList = new List<Person>();
            String selectFromMysqlDatabase = "SELECT * FROM `csharpandmysqlcrudinsertupdatedeleteselecttable` WHERE CONCAT_WS(' ', `Id`, `FirstName`, `LastName`, `Email`, `Gender`, `Language`, `Country`, `ImageName`, `ImagePath`, `ImageBlob`) LIKE '%"+ valueToSearch+"%' ";
            MySqlCommand command;
            MySqlDataReader reader;
            Person person;

            dbCONN.openDBConnection();
            try
            {
                command = new MySqlCommand(selectFromMysqlDatabase, dbCONN.getDatabaseConnection());
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    person = new Person();
                    person.Id = Convert.ToInt32(reader[0].ToString());
                        //.GetInt32(reader[0].ToString());
                    person.FirstName = reader[1].ToString();
                    person.LastName = reader[2].ToString();
                    person.Email = reader[3].ToString();
                    person.Gender = reader[4].ToString();
                    person.Language = reader[5].ToString();
                    person.Country = reader[6].ToString();
                    person.ImageName = reader[7].ToString();
                    person.ImagePath = reader[8].ToString();
                    person.ImageBlob = (byte[])reader[9];

                    personList.Add(person);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("Error " + err.StackTrace);
            }
            finally
            {
                //reader.Close();
                //command.Dispose();
                dbCONN.closeDBConnection();

            }

            return personList;

        }
    }
}

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #38 – How To Read Mysql Rows(Data) And Store Them In Array List


How To Populate (Bind) Datagridview From List Of Items In C#

C# SOURCE CODE

        private void refreshDatagridView(string searchValue)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.RowTemplate.Height = 45;

            BindingSource bsource = new BindingSource();
            PersonData pData = new PersonData();
            bsource.DataSource = pData.PersonList(searchValue);
            dataGridView1.DataSource = bsource;

            //Fit Image In DataGridView Cell
            DataGridViewImageColumn dGVimageColumn = (DataGridViewImageColumn)dataGridView1.Columns[9];
            dGVimageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #39 – How To Populate (Bind) Datagridview From List Of Items


How To Move a Line(Selected Code) Up or Down in Visual Studio

This involves moving the selected line of code up or down using keyboard shortcut. To do this you need to add appropriate plugin to your IDE (Visual Studio 2010).

You can easily move lines up and down using MoveLine Extension.
Download Link – https://marketplace.visualstudio.com/items?itemName=KevinAenmey.MoveLine

How to Move Selected Code Up or Down in Visual Studio - Homepage
How to Move Selected Code Up or Down in Visual Studio – Homepage


To Download “Move Line Extension Using Visual Studio 2010” :

Step 1. Go Tools

 How to Move Selected Code Up or Down in Visual Studio - Tools
How to Move Selected Code Up or Down in Visual Studio – Tools


Step 2. Choose Extension Manager.

 How to Move Selected Code Up or Down in Visual Studio - Extension Manager
How to Move Selected Code Up or Down in Visual Studio – Extension Manager


Step 3. From the left pane select “Online Gallery”.

 How to Move Selected Code Up or Down in Visual Studio - Online gallery
How to Move Selected Code Up or Down in Visual Studio – Online gallery


Step 4. Type The name of the extension in the search box. In this Case “MoveLine”;

 How to Move Selected Code Up or Down in Visual Studio - Search MoveLine
How to Move Selected Code Up or Down in Visual Studio – Search MoveLine


Step 5. Then Click Download.

 How to Move Selected Code Up or Down in Visual Studio - Install MoveLine
How to Move Selected Code Up or Down in Visual Studio – Install MoveLine


Step 6. When The Download Finishes, restart your IDE.

 How to Move Selected Code Up or Down in Visual Studio - Restart IDE Visual Studio 2010
How to Move Selected Code Up or Down in Visual Studio – Restart IDE Visual Studio 2010

If you go back to extension manager, you will see that the extension has been added.

 How to Move Selected Code Up or Down in Visual Studio - Installed
How to Move Selected Code Up or Down in Visual Studio – Installed


To move single line or selected block of code (Multiple Lines) use the keyboard shortcuts below.

The default shortcut keys are as follows:

Alt+Up Arrow – Moves a line up
Alt+Down Arrow – Moves a line down

To change the shortcut keys:

In the Visual Studio main menu go to Tools -> Options
Expand Environment
Select Keyboard
In the Show commands containing box type Tools.MoveLineUp orTools.MoveLineDown
In the Press shortcut keys box press the new shortcut keys
Click Assign

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #40 – How to Move a Line(Selected Code) Up or Down in Visual Studio


How To Check If Datagridview Row Is Selected Or Not In C#

It’s good to check if a row is selected before performing a task on it. Failure to that results in unwanted errors.

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #41 – How To Check If Datagridview Row Is Selected Or Not


How To Get Datagridview Currently Selected Row Index On Row click C#

Selected row has a unique index starting from 0.

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #42 – How To Get Datagridview Currently Selected Row Index On Row click


How To Display Selected Row From Datagridview To Textboxes In C#

Selected row values are displayed in textboxes when you click on datagridview row.

C# SOURCE CODE

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Check If there is a row selected

            if (dataGridView1.SelectedRows.Count > 0)
            {
                selectedRowIndex = e.RowIndex;
                // Selected Row
                //MessageBox.Show("Selected Row Index >>>>>> -- " + selectedRowIndex);

                DataGridViewRow selectedDGVRow = dataGridView1.Rows[selectedRowIndex];
                //Diplaying Selected DataGridView row data On Textboxes
                textBoxID.Text = selectedDGVRow.Cells[0].Value.ToString();
                textBoxFirstName.Text = selectedDGVRow.Cells[1].Value.ToString();
                textBoxLastName.Text = selectedDGVRow.Cells[2].Value.ToString();
                textBoxEmail.Text = selectedDGVRow.Cells[3].Value.ToString();
                //Check if datagridview cell value matches with radio button value 
                if (selectedDGVRow.Cells[4].Value.ToString().Equals("Male"))
                {
                    //Diplaying Selected DataGridView row data On radio button
                    radioButtonMale.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[4].Value.ToString().Equals("Female"))
                    {
                        //Diplaying Selected DataGridView row data On radio button
                        radioButtonFemale.Checked = true;
                    }
                if (selectedDGVRow.Cells[5].Value.ToString().Equals("English"))
                {
                    //Diplaying Selected DataGridView row data On checkbox
                    checkBoxEnglish.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[5].Value.ToString().Equals("Arabic"))
                    {
                        //Diplaying Selected DataGridView row data On checkbox
                        checkBoxArabic.Checked = true;
                    }

                comboBoxCountry.Text = selectedDGVRow.Cells[6].Value.ToString();
                textBoxImageName.Text = selectedDGVRow.Cells[7].Value.ToString();
                textBoxImagePath.Text = selectedDGVRow.Cells[8].Value.ToString();
                //Diplaying Selected DataGridView row data On PictureBox
                byte[] imgB = (byte[])selectedDGVRow.Cells[9].Value;
                MemoryStream ms = new MemoryStream(imgB);
                pictureBox1.Image = Image.FromStream(ms);
            }
            else
            {

                //No Row Selected
            }
        }
How To Get Datagridview Currently Selected Row Index On Row click C
How To Get Datagridview Currently Selected Row Index On Row click C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #43 – How To Display Selected Row From Datagridview Into Textboxes


How To Display Selected Row Image From Datagridview To Picturebox C#

The image from datagridview is displayed in picturebox when you click on datagridview row.

C# SOURCE CODE

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Check If there is a row selected

            if (dataGridView1.SelectedRows.Count > 0)
            {
                selectedRowIndex = e.RowIndex;
                // Selected Row
                //MessageBox.Show("Selected Row Index >>>>>> -- " + selectedRowIndex);

                DataGridViewRow selectedDGVRow = dataGridView1.Rows[selectedRowIndex];
                //Diplaying Selected DataGridView row data On Textboxes
                textBoxID.Text = selectedDGVRow.Cells[0].Value.ToString();
                textBoxFirstName.Text = selectedDGVRow.Cells[1].Value.ToString();
                textBoxLastName.Text = selectedDGVRow.Cells[2].Value.ToString();
                textBoxEmail.Text = selectedDGVRow.Cells[3].Value.ToString();
                //Check if datagridview cell value matches with radio button value 
                if (selectedDGVRow.Cells[4].Value.ToString().Equals("Male"))
                {
                    //Diplaying Selected DataGridView row data On radio button
                    radioButtonMale.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[4].Value.ToString().Equals("Female"))
                    {
                        //Diplaying Selected DataGridView row data On radio button
                        radioButtonFemale.Checked = true;
                    }
                if (selectedDGVRow.Cells[5].Value.ToString().Equals("English"))
                {
                    //Diplaying Selected DataGridView row data On checkbox
                    checkBoxEnglish.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[5].Value.ToString().Equals("Arabic"))
                    {
                        //Diplaying Selected DataGridView row data On checkbox
                        checkBoxArabic.Checked = true;
                    }

                comboBoxCountry.Text = selectedDGVRow.Cells[6].Value.ToString();
                textBoxImageName.Text = selectedDGVRow.Cells[7].Value.ToString();
                textBoxImagePath.Text = selectedDGVRow.Cells[8].Value.ToString();
                //Diplaying Selected DataGridView row data On PictureBox
                byte[] imgB = (byte[])selectedDGVRow.Cells[9].Value;
                MemoryStream ms = new MemoryStream(imgB);
                pictureBox1.Image = Image.FromStream(ms);
            }
            else
            {

                //No Row Selected
            }
        }
How To Display Selected Row Image From Datagridview To Picturebox C
How To Display Selected Row Image From Datagridview To Picturebox C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #44 – How To Display Selected Image From Datagridview Row To Picturebox


How To Display Selected Row Value From Datagridview To RadioButton C#

Radio button gets selected when you click on datagridview row with the value that matches radio button value.

C# SOURCE CODE

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Check If there is a row selected

            if (dataGridView1.SelectedRows.Count > 0)
            {
                selectedRowIndex = e.RowIndex;
                // Selected Row
                //MessageBox.Show("Selected Row Index >>>>>> -- " + selectedRowIndex);

                DataGridViewRow selectedDGVRow = dataGridView1.Rows[selectedRowIndex];
                //Diplaying Selected DataGridView row data On Textboxes
                textBoxID.Text = selectedDGVRow.Cells[0].Value.ToString();
                textBoxFirstName.Text = selectedDGVRow.Cells[1].Value.ToString();
                textBoxLastName.Text = selectedDGVRow.Cells[2].Value.ToString();
                textBoxEmail.Text = selectedDGVRow.Cells[3].Value.ToString();
                //Check if datagridview cell value matches with radio button value 
                if (selectedDGVRow.Cells[4].Value.ToString().Equals("Male"))
                {
                    //Diplaying Selected DataGridView row data On radio button
                    radioButtonMale.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[4].Value.ToString().Equals("Female"))
                    {
                        //Diplaying Selected DataGridView row data On radio button
                        radioButtonFemale.Checked = true;
                    }
                if (selectedDGVRow.Cells[5].Value.ToString().Equals("English"))
                {
                    //Diplaying Selected DataGridView row data On checkbox
                    checkBoxEnglish.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[5].Value.ToString().Equals("Arabic"))
                    {
                        //Diplaying Selected DataGridView row data On checkbox
                        checkBoxArabic.Checked = true;
                    }

                comboBoxCountry.Text = selectedDGVRow.Cells[6].Value.ToString();
                textBoxImageName.Text = selectedDGVRow.Cells[7].Value.ToString();
                textBoxImagePath.Text = selectedDGVRow.Cells[8].Value.ToString();
                //Diplaying Selected DataGridView row data On PictureBox
                byte[] imgB = (byte[])selectedDGVRow.Cells[9].Value;
                MemoryStream ms = new MemoryStream(imgB);
                pictureBox1.Image = Image.FromStream(ms);
            }
            else
            {

                //No Row Selected
            }
        }
How To Display Selected Row Value From Datagridview To RadioButton C
How To Display Selected Row Value From Datagridview To RadioButton C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #45 – How To Display Selected Row Value From Datagridview To RadioButton


How To Display Selected Row Value From Datagridview To CheckBox C#

CheckBox gets checked when you click on datagridview row with the value that matches CheckBox value.

C# SOURCE CODE

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Check If there is a row selected

            if (dataGridView1.SelectedRows.Count > 0)
            {
                selectedRowIndex = e.RowIndex;
                // Selected Row
                //MessageBox.Show("Selected Row Index >>>>>> -- " + selectedRowIndex);

                DataGridViewRow selectedDGVRow = dataGridView1.Rows[selectedRowIndex];
                //Diplaying Selected DataGridView row data On Textboxes
                textBoxID.Text = selectedDGVRow.Cells[0].Value.ToString();
                textBoxFirstName.Text = selectedDGVRow.Cells[1].Value.ToString();
                textBoxLastName.Text = selectedDGVRow.Cells[2].Value.ToString();
                textBoxEmail.Text = selectedDGVRow.Cells[3].Value.ToString();
                //Check if datagridview cell value matches with radio button value 
                if (selectedDGVRow.Cells[4].Value.ToString().Equals("Male"))
                {
                    //Diplaying Selected DataGridView row data On radio button
                    radioButtonMale.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[4].Value.ToString().Equals("Female"))
                    {
                        //Diplaying Selected DataGridView row data On radio button
                        radioButtonFemale.Checked = true;
                    }
                if (selectedDGVRow.Cells[5].Value.ToString().Equals("English"))
                {
                    //Diplaying Selected DataGridView row data On checkbox
                    checkBoxEnglish.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[5].Value.ToString().Equals("Arabic"))
                    {
                        //Diplaying Selected DataGridView row data On checkbox
                        checkBoxArabic.Checked = true;
                    }

                comboBoxCountry.Text = selectedDGVRow.Cells[6].Value.ToString();
                textBoxImageName.Text = selectedDGVRow.Cells[7].Value.ToString();
                textBoxImagePath.Text = selectedDGVRow.Cells[8].Value.ToString();
                //Diplaying Selected DataGridView row data On PictureBox
                byte[] imgB = (byte[])selectedDGVRow.Cells[9].Value;
                MemoryStream ms = new MemoryStream(imgB);
                pictureBox1.Image = Image.FromStream(ms);
            }
            else
            {

                //No Row Selected
            }
        }
How To Display Selected Row Value From Datagridview To CheckBox C
How To Display Selected Row Value From Datagridview To CheckBox C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #46 – How To Display Selected Row Value From Datagridview To CheckBox


How To Display Selected Row Value From Datagridview To ComboBox C#

ComboBox displays the appropriate value when you click on datagridview row.

C# SOURCE CODE

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Check If there is a row selected

            if (dataGridView1.SelectedRows.Count > 0)
            {
                selectedRowIndex = e.RowIndex;
                // Selected Row
                //MessageBox.Show("Selected Row Index >>>>>> -- " + selectedRowIndex);

                DataGridViewRow selectedDGVRow = dataGridView1.Rows[selectedRowIndex];
                //Diplaying Selected DataGridView row data On Textboxes
                textBoxID.Text = selectedDGVRow.Cells[0].Value.ToString();
                textBoxFirstName.Text = selectedDGVRow.Cells[1].Value.ToString();
                textBoxLastName.Text = selectedDGVRow.Cells[2].Value.ToString();
                textBoxEmail.Text = selectedDGVRow.Cells[3].Value.ToString();
                //Check if datagridview cell value matches with radio button value 
                if (selectedDGVRow.Cells[4].Value.ToString().Equals("Male"))
                {
                    //Diplaying Selected DataGridView row data On radio button
                    radioButtonMale.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[4].Value.ToString().Equals("Female"))
                    {
                        //Diplaying Selected DataGridView row data On radio button
                        radioButtonFemale.Checked = true;
                    }
                if (selectedDGVRow.Cells[5].Value.ToString().Equals("English"))
                {
                    //Diplaying Selected DataGridView row data On checkbox
                    checkBoxEnglish.Checked = true;
                }
                else
                    if (selectedDGVRow.Cells[5].Value.ToString().Equals("Arabic"))
                    {
                        //Diplaying Selected DataGridView row data On checkbox
                        checkBoxArabic.Checked = true;
                    }

                comboBoxCountry.Text = selectedDGVRow.Cells[6].Value.ToString();
                textBoxImageName.Text = selectedDGVRow.Cells[7].Value.ToString();
                textBoxImagePath.Text = selectedDGVRow.Cells[8].Value.ToString();
                //Diplaying Selected DataGridView row data On PictureBox
                byte[] imgB = (byte[])selectedDGVRow.Cells[9].Value;
                MemoryStream ms = new MemoryStream(imgB);
                pictureBox1.Image = Image.FromStream(ms);
            }
            else
            {

                //No Row Selected
            }
        }
How To Display Selected Row Value From Datagridview To ComboBox C
How To Display Selected Row Value From Datagridview To ComboBox C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #47 – How To Display Selected Row Value From Datagridview To ComboBox


How To clear Or Reset a combobox On Button Click In C#

Clearing combobox on button click.

How To clear Or Reset a combobox On Button Click In C
How To clear Or Reset a combobox On Button Click In C

C# SOURCE CODE

        //Resetting/Clearing Textfields Function
        private void clearFields()
        {
            //Resetting/Clearing Textfields
            textBoxID.Text = String.Empty;
            textBoxFirstName.Text = String.Empty;
            textBoxLastName.Text = String.Empty;
            textBoxEmail.Text = String.Empty;
            textBoxImageName.Text = String.Empty;
            textBoxImagePath.Text = String.Empty;
            textBoxSearch.Text = String.Empty;
            //Clearing Picturebox
            pictureBox1.Image = null;
            //Clearing Combobox
            comboBoxCountry.Text = String.Empty;           
            //Clearing/resetting Radiobuttons
            if (radioButtonMale.Checked)
            {
                radioButtonMale.Checked = false;
            }
            else
                if (radioButtonFemale.Checked)
                {
                    radioButtonFemale.Checked = false;
                }
            //Clearing/resetting CheckBoxes
            if (checkBoxEnglish.Checked)
            {
                checkBoxEnglish.Checked = false;
            }
            else
                if (checkBoxArabic.Checked)
                {
                    checkBoxArabic.Checked = false;
                }

            //Refresh Datagridview After clearing fields
            refreshDatagridView("");

        }

VIDEO TUTORIAL

How To clear Or Reset a combobox On Button Click In C


How To clear Or Reset Radio Button On Button Click In C#

Resetting all radio buttons on button click.

How To clear Or Reset Radio Button On Button Click In C
How To clear Or Reset Radio Button On Button Click In C

C# SOURCE CODE

        //Resetting/Clearing Textfields Function
        private void clearFields()
        {
            //Resetting/Clearing Textfields
            textBoxID.Text = String.Empty;
            textBoxFirstName.Text = String.Empty;
            textBoxLastName.Text = String.Empty;
            textBoxEmail.Text = String.Empty;
            textBoxImageName.Text = String.Empty;
            textBoxImagePath.Text = String.Empty;
            textBoxSearch.Text = String.Empty;
            //Clearing Picturebox
            pictureBox1.Image = null;
            //Clearing Combobox
            comboBoxCountry.Text = String.Empty;           
            //Clearing/resetting Radiobuttons
            if (radioButtonMale.Checked)
            {
                radioButtonMale.Checked = false;
            }
            else
                if (radioButtonFemale.Checked)
                {
                    radioButtonFemale.Checked = false;
                }
            //Clearing/resetting CheckBoxes
            if (checkBoxEnglish.Checked)
            {
                checkBoxEnglish.Checked = false;
            }
            else
                if (checkBoxArabic.Checked)
                {
                    checkBoxArabic.Checked = false;
                }

            //Refresh Datagridview After clearing fields
            refreshDatagridView("");

        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #49 – How To clear Or Reset Radio Button On Button Click


How To clear Or Reset Check Box On Button Click In C#

Unchecking all checkboxes on button click.

How To clear Or Reset Check Box On Button Click In C
How To clear Or Reset Check Box On Button Click In C

C# SOURCE CODE

        //Resetting/Clearing Textfields Function
        private void clearFields()
        {
            //Resetting/Clearing Textfields
            textBoxID.Text = String.Empty;
            textBoxFirstName.Text = String.Empty;
            textBoxLastName.Text = String.Empty;
            textBoxEmail.Text = String.Empty;
            textBoxImageName.Text = String.Empty;
            textBoxImagePath.Text = String.Empty;
            textBoxSearch.Text = String.Empty;
            //Clearing Picturebox
            pictureBox1.Image = null;
            //Clearing Combobox
            comboBoxCountry.Text = String.Empty;           
            //Clearing/resetting Radiobuttons
            if (radioButtonMale.Checked)
            {
                radioButtonMale.Checked = false;
            }
            else
                if (radioButtonFemale.Checked)
                {
                    radioButtonFemale.Checked = false;
                }
            //Clearing/resetting CheckBoxes
            if (checkBoxEnglish.Checked)
            {
                checkBoxEnglish.Checked = false;
            }
            else
                if (checkBoxArabic.Checked)
                {
                    checkBoxArabic.Checked = false;
                }

            //Refresh Datagridview After clearing fields
            refreshDatagridView("");

        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #51 – How To clear Or Reset Text Boxes On Button Click


How To clear Or Reset Text Boxes On Button Click In C#

Clearing all textbox values on button click. Empty values are assigned to Textbox in this scenario.

How To clear Or Reset Text Boxes On Button Click In C
How To clear Or Reset Text Boxes On Button Click In C

C# SOURCE CODE

        //Resetting/Clearing Textfields Function
        private void clearFields()
        {
            //Resetting/Clearing Textfields
            textBoxID.Text = String.Empty;
            textBoxFirstName.Text = String.Empty;
            textBoxLastName.Text = String.Empty;
            textBoxEmail.Text = String.Empty;
            textBoxImageName.Text = String.Empty;
            textBoxImagePath.Text = String.Empty;
            textBoxSearch.Text = String.Empty;
            //Clearing Picturebox
            pictureBox1.Image = null;
            //Clearing Combobox
            comboBoxCountry.Text = String.Empty;           
            //Clearing/resetting Radiobuttons
            if (radioButtonMale.Checked)
            {
                radioButtonMale.Checked = false;
            }
            else
                if (radioButtonFemale.Checked)
                {
                    radioButtonFemale.Checked = false;
                }
            //Clearing/resetting CheckBoxes
            if (checkBoxEnglish.Checked)
            {
                checkBoxEnglish.Checked = false;
            }
            else
                if (checkBoxArabic.Checked)
                {
                    checkBoxArabic.Checked = false;
                }

            //Refresh Datagridview After clearing fields
            refreshDatagridView("");

        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #51 – How To clear Or Reset Text Boxes On Button Click


How To clear Or Reset Image On A Picturebox On Button Click In C#

Clearing image from picture box on button click. This sets value of a picture box Image to null.

How To clear Or Reset Image On A Picturebox On Button Click In C
How To clear Or Reset Image On A Picturebox On Button Click In C

C# SOURCE CODE

        //Resetting/Clearing Textfields Function
        private void clearFields()
        {
            //Resetting/Clearing Textfields
            textBoxID.Text = String.Empty;
            textBoxFirstName.Text = String.Empty;
            textBoxLastName.Text = String.Empty;
            textBoxEmail.Text = String.Empty;
            textBoxImageName.Text = String.Empty;
            textBoxImagePath.Text = String.Empty;
            textBoxSearch.Text = String.Empty;
            //Clearing Picturebox
            pictureBox1.Image = null;
            //Clearing Combobox
            comboBoxCountry.Text = String.Empty;           
            //Clearing/resetting Radiobuttons
            if (radioButtonMale.Checked)
            {
                radioButtonMale.Checked = false;
            }
            else
                if (radioButtonFemale.Checked)
                {
                    radioButtonFemale.Checked = false;
                }
            //Clearing/resetting CheckBoxes
            if (checkBoxEnglish.Checked)
            {
                checkBoxEnglish.Checked = false;
            }
            else
                if (checkBoxArabic.Checked)
                {
                    checkBoxArabic.Checked = false;
                }

            //Refresh Datagridview After clearing fields
            refreshDatagridView("");

        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #52 – How To clear Or Reset Image On A Picturebox On Button Click


How To Make Only One Checkbox Checked At A Time C#

Uncheck one checkbox when the other is checked.

C# SOURCE CODE

        //Resetting/Clearing Textfields Function
        private void clearFields()
        {
            //Resetting/Clearing Textfields
            textBoxID.Text = String.Empty;
            textBoxFirstName.Text = String.Empty;
            textBoxLastName.Text = String.Empty;
            textBoxEmail.Text = String.Empty;
            textBoxImageName.Text = String.Empty;
            textBoxImagePath.Text = String.Empty;
            textBoxSearch.Text = String.Empty;
            //Clearing Picturebox
            pictureBox1.Image = null;
            //Clearing Combobox
            comboBoxCountry.Text = String.Empty;           
            //Clearing/resetting Radiobuttons
            if (radioButtonMale.Checked)
            {
                radioButtonMale.Checked = false;
            }
            else
                if (radioButtonFemale.Checked)
                {
                    radioButtonFemale.Checked = false;
                }
            //Clearing/resetting CheckBoxes
            if (checkBoxEnglish.Checked)
            {
                checkBoxEnglish.Checked = false;
            }
            else
                if (checkBoxArabic.Checked)
                {
                    checkBoxArabic.Checked = false;
                }

            //Refresh Datagridview After clearing fields
            refreshDatagridView("");

        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #53 – How To Make Only One Checkbox Checked At A Time


How To Disable Text Input [Editing] In TextBox In C#

Disabling text input in textbox.

Select textbox, go to properties and change “enabled” property value to false.

This makes a textbox completely disabled. If you want to revert this change Enabled property value to “True”.

How To Disable Text Input Editing In TextBox In C - Enable False
How To Disable Text Input Editing In TextBox In C – Enable False
How To Disable Text Input Editing In TextBox In C
How To Disable Text Input Editing In TextBox In C

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #54 – How To Disable Text Input Or Editing In TextBox


How To Check If Input Fields Are Empty In C#

Checking if input fields are empty before inserting their values to the database. If one of the field is blank you will not be able to insert data into the database.

C# SOURCE CODE

            if (string.IsNullOrEmpty(textBoxFirstName.Text) || string.IsNullOrEmpty(textBoxLastName.Text) || string.IsNullOrEmpty(textBoxEmail.Text) || string.IsNullOrEmpty(textBoxImageName.Text) || string.IsNullOrEmpty(textBoxImagePath.Text) || string.IsNullOrEmpty(comboBoxCountry.Text) || pictureBox1.Image == null)
            {
                //If there is one or more empty fields output this message
                MessageBox.Show("one or more empty fields. Fill All The Fields");

            }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #55 – How To Check If Input Fields Are Empty


How To Delete Data From Table In MySql Using C#

Removing a row from Mysql database by clicking a button. Select the row you want to delete from the datagridview. So long as ID field has data you will be able to delete it from the database.

How To Delete Data From Table In MySql Using C
How To Delete Data From Table In MySql Using C

C# SOURCE CODE

        //Deleting data from mysql database
        private void button4_Click(object sender, EventArgs e)
        {

            //First Check if the textbox field is empty

            if (string.IsNullOrEmpty(textBoxID.Text))
            {
                MessageBox.Show("Id Field Is Empty First Click On Datagrid Cell To populate it with a value");

            }
            else
            {
                string deleteSQLQuery = "DELETE FROM `csharpandmysqlcrudinsertupdatedeleteselecttable` WHERE `Id` = @Id";
                MySqlCommand deleteCommand;

                try
                {
                    //Open Database Connection
                    dbCONN.openDBConnection();
                    deleteCommand = new MySqlCommand(deleteSQLQuery, dbCONN.getDatabaseConnection());
                    deleteCommand.Parameters.Add("@Id", MySqlDbType.Int32).Value = int.Parse(textBoxID.Text);

                    //Check If The Data has been deleted
                    if (deleteCommand.ExecuteNonQuery() == 1)
                    {
                        MessageBox.Show("Data Deleted Successfully..... ");
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show("Err " + err);
                }
                finally
                {
                    //close Database Connection
                    dbCONN.closeDBConnection();
                }
                //clear input fields after Deleting data from mysql database
                clearFields();
                //Refresh datagridview after deleting data from database
                refreshDatagridView("");
            }
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #56 – How To Delete Data From MySql Table


How To Refresh Datagridview Rows After Change In MySql C#

Reloading the rows after any database change.

How To Refresh Datagridview Rows After Change In MySql C
How To Refresh Datagridview Rows After Change In MySql C

C# SOURCE CODE

//CALLING THIS FUNCTION REFRESHES DATAGRIDVIEW
        private void refreshDatagridView(string searchValue)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.RowTemplate.Height = 45;

            BindingSource bsource = new BindingSource();
            PersonData pData = new PersonData();
            bsource.DataSource = pData.PersonList(searchValue);
            dataGridView1.DataSource = bsource;

            //Fit Image In DataGridView Cell
            DataGridViewImageColumn dGVimageColumn = (DataGridViewImageColumn)dataGridView1.Columns[9];
            dGVimageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #57 – How To Refresh Datagridview Rows After Change In MySql


How To Update Data From Table In MySql Using C#

Updating Mysql database on button click. To update a row first select it from the datagridview, the input fields gets populated with the selected row data. Edit the data then click update button.

How To Update Data From Table In MySql Using C
How To Update Data From Table In MySql Using C

C# SOURCE CODE

        //Updating Mysql Database Row
        private void button3_Click(object sender, EventArgs e)
        {

            //First check if there is any empty field

            //Check If Input Fields Are Empty before inserting to the database
            //Check if textboxes are empty
            //Check if Combobox Field is empty
            //Check if Picturebox Field is empty


            if (string.IsNullOrEmpty(textBoxFirstName.Text) || string.IsNullOrEmpty(textBoxLastName.Text) || string.IsNullOrEmpty(textBoxEmail.Text) || string.IsNullOrEmpty(textBoxImageName.Text) || string.IsNullOrEmpty(textBoxImagePath.Text) || string.IsNullOrEmpty(comboBoxCountry.Text) || pictureBox1.Image == null)
            {
                //If there is one or more empty fields output this message
                MessageBox.Show("one or more empty fields. Fill All The Fields");

            }
            else
            {


                string updateSQLQuery = "UPDATE `csharpandmysqlcrudinsertupdatedeleteselecttable` SET `FirstName`=@FirstName,`LastName`=@LastName,`Email`=@Email,`Gender`=@Gender,`Language`=@Language,`Country`=@Country,`ImageName`=@ImageName,`ImagePath`=@ImagePath,`ImageBlob`=@ImageBlob WHERE `Id` = @Id";
                MySqlCommand updateCommand;

                //Check Which CheckBox Is Checked
                if (checkBoxEnglish.Checked)
                {
                    languageCheckBox = "English";
                }
                else
                    if (checkBoxArabic.Checked)
                    {
                        languageCheckBox = "Arabic";
                    }

                //Check Which Button Is Checked
                if (radioButtonMale.Checked)
                {
                    radioButtonValueGender = "Male";
                }
                else
                    if (radioButtonFemale.Checked)
                    {
                        radioButtonValueGender = "Female";
                    }
                countryCombobox = comboBoxCountry.SelectedItem.ToString();

                MemoryStream ms = new MemoryStream();
                pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
                Byte[] img = ms.ToArray();


                try
                {
                    //Open Connection
                    dbCONN.openDBConnection();
                    updateCommand = new MySqlCommand(updateSQLQuery, dbCONN.getDatabaseConnection());
                    updateCommand.Parameters.Add("@FirstName", MySqlDbType.VarChar).Value = textBoxFirstName.Text;
                    updateCommand.Parameters.Add("@LastName", MySqlDbType.VarChar).Value = textBoxLastName.Text;
                    updateCommand.Parameters.Add("@Email", MySqlDbType.VarChar).Value = textBoxEmail.Text;
                    updateCommand.Parameters.Add("@Gender", MySqlDbType.VarChar).Value = radioButtonValueGender;
                    updateCommand.Parameters.Add("@Language", MySqlDbType.VarChar).Value = languageCheckBox;
                    updateCommand.Parameters.Add("@Country", MySqlDbType.VarChar).Value = countryCombobox;
                    updateCommand.Parameters.Add("@ImageName", MySqlDbType.VarChar).Value = textBoxImageName.Text;
                    updateCommand.Parameters.Add("@ImagePath", MySqlDbType.VarChar).Value = textBoxImagePath.Text;
                    updateCommand.Parameters.Add("@ImageBlob", MySqlDbType.Blob).Value = img;
                    updateCommand.Parameters.Add("@Id", MySqlDbType.VarChar).Value = int.Parse(textBoxID.Text);

                    //check if data has been updated
                    if (updateCommand.ExecuteNonQuery() == 1)
                    {
                        MessageBox.Show("Data Updated Successfully......");
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show("Error " + err);
                }
                finally
                {
                    //close database connection
                    dbCONN.closeDBConnection();
                }
                //clear input fields after updating data in mysql database
                clearFields();
                //Refresh datagridview to display updated data
                refreshDatagridView("");
            }
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #58 – How To Update Data From Table In MySql


How To Search Data From MySql and Filter in datagridview Table In C#

To search for a specific data enter the keywords in the search textbox. Datagridview displays data that matches your keyword on keypress.

How To Search Data From MySql and Filter in datagridview Table In C
How To Search Data From MySql and Filter in datagridview Table In C

C# SOURCE CODE

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            string val = textBoxSearch.Text;
            refreshDatagridView(val);
        }

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #59 – How To Search Data From MySql and Filter in datagridview Table


Fixing (GUI) Graphical User Interface

VIDEO TUTORIAL

C# AND MYSQL DATABASE CRUD TUTORIAL #60 – Fixing (GUI) Graphical User Interface


Complete Video Tutorial

C# AND MYSQL DATABASE CRUD TUTORIAL #61 – Insert Update Search Delete And Display Data On DataGridView Using Visual Studio 2010 Complete Video Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *