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
- How To Insert Update Search Delete And Display Data On DataGridView – Demo Video (Overview) – Project Walk-Through
- How To Create A New Form
- How To Display The Form At The Center Screen
- How To Add Panel To A Form
- How To Change Or Set Form Background Color
- How To Add Labels In A Form
- How To Add TextBoxes In A Form
- How To Add RadioButtons On A Form
- How To Add CheckBoxes On A Form
- How To Add Combobox On A Form
- How To Add Buttons On A Form
- How To Add Table On A Form
- How To Add Picturebox On A Form
- How To Add Image Icon On A Button
- How To Browse And Display Image On PictureBox
- How To Resize Image To Fit PictureBox
- How To Filter Image Types (Png, Jpg, Gif) (OpenFileDialog)
- How To Display Image Absolute Path (OpenFileDialog)
- How To Download Mysql Connector For Visual Studio C# Project
- How To Add Mysql Connector To Visual Studio 2010 Project
- How To Create New MySql Database Using PHPMyAdmin
- How To Connect To MySql Database – Part 1
- 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
- How To Connect To MySql Database – Part 4 – Check Connection [XAMPP]
- How To Connect To MySql Database – Part 5 Opening Connection Function
- How To Connect To MySql Database – Part 6 Closing Connection Function
- How To Insert TextBox Text, Value, Data Into MySql Database – Part 1
- How To Insert TextBox Text, Value, Data Into MySql Database – Part 2
- How To Obtain Only The Filename (OpenFileDialog) Insert Into Db – Part 3
- How To Insert Radio Button Values, Data Into MySql Database
- How To Insert Checkbox Value, Data Into Database Using C#
- How To Insert Combobox Selected Item, Value Into Mysql In C#
- How To Save Or Insert Image Into Mysql Database In C#
- How To Retrieve Data From Mysql And Display It On DataGridView In C#
- How To Automatically Adjust Columns Width To Fit In The DataGridView In C#
- How To Increase (Change Or Set) DataGridView Row Height In C#
- How To Stretch An Image In C# DataGridView Fit Image In Column Row Cell
- How To Create Getter And Setter, Constructor In C# – Shortcut
- How To Read Mysql Data And Store Them In Array List C#
- How To Populate (Bind) Datagridview From List Of Items In C#
- 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#
- How To Get Datagridview Currently Selected Row Index On Row click C#
- How To Display Selected Row From Datagridview To Textboxes In C#
- How To Display Selected Row Image From Datagridview To Picturebox C#
- How To Display Selected Row Value From Datagridview To RadioButton C#
- How To Display Selected Row Value From Datagridview To CheckBox C#
- How To Display Selected Row Value From Datagridview To ComboBox C#
- How To clear Or Reset a combobox On Button Click In C#
- How To clear Or Reset Radio Button On Button Click In C#
- How To clear Or Reset Check Box On Button Click In C#
- How To clear Or Reset Text Boxes On Button Click In C#
- How To clear Or Reset Image On A Picturebox On Button Click In C#
- How To Make Only One Checkbox Checked At A Time C#
- How To Disable Text Input [Editing] In TextBox In C#
- How To Check If Input Fields Are Empty In C#
- How To Delete Data From Table In MySql Using C#
- How To Refresh Datagridview Rows After Change In MySql C#
- How To Update Data From Table In MySql Using C#
- How To Search Data From MySql and Filter in datagridview Table In C#
- Fixing (GUI) Graphical User Interface
- 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
How To Create A New Form
Start Visual Studio 2010.
Select the File menu, then New, then 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.

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.

Solution Explorer Shows the files created for your project.

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.

This is the location you chose when creating new project.

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
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.

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

VIDEO TUTORIAL
How To Add Panel To A Form
Drag and drop panel from toolbox onto the form.

VIDEO TUTORIAL
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.

VIDEO TUTORIAL
How To Add Labels In A Form
Drag and drop label from toolbox onto the form.

VIDEO TUTORIAL
How To Add TextBoxes In A Form
Drag and drop TextBox from toolbox onto the form.

VIDEO TUTORIAL
How To Add RadioButtons On A Form
Drag and drop RadioButton from toolbox onto the form.

VIDEO TUTORIAL
How To Add CheckBoxes On A Form
Drag and drop CheckBox from toolbox onto the form.

VIDEO TUTORIAL
How To Add Combobox On A Form
Drag and drop ComboBox from toolbox onto the form.

VIDEO TUTORIAL
How To Add Buttons On A Form
Drag and drop Button from toolbox onto the form.

VIDEO TUTORIAL
How To Add DataGridView (Table) On A Form
Drag and drop DataGridView from toolbox onto the form.

VIDEO TUTORIAL
How To Add Picturebox On A Form
Drag and drop PictureBox from toolbox onto the form.

VIDEO TUTORIAL
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.

Select resources tab.
Then from Add resource dropdown, Select Add Existing File.

Select icons from your computer and click open.

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

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

VIDEO TUTORIAL
How To Browse And Display Image On PictureBox
Browse button opens dialog box where you can choose image from your computer.

Choose one image from your PC and click open.

After you click open the image is displayed on picturebox.

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
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.

Change Size Mode To “StretchImage”.

C# SOURCE CODE
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
VIDEO TUTORIAL
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
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.

C# SOURCE CODE
//Displaying image path On Disabled textbox. textBoxImagePath.Text = ofd.FileName;
VIDEO TUTORIAL
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.

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

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

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.

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

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

Step 7 – Select The Downloaded Zip file.

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

Step 9 – The files are extracted to specified 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).

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

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.

VIDEO TUTORIAL
How To Add Mysql Connector To Visual Studio 2010 Project
Right Click on project name from solution explorer.
Select add reference.

click on browse tab.
Locate the connector folder and open it.
Select MySql.Data.Dll.
Click Ok.

Mysql.Data is added to references section.
This means mysql connector/NET has been added in your project successfully.

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

VIDEO TUTORIAL
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.

Start both Apache and Mysql.

Both services are now running.

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

Click New To create new database.

Enter database name and click create button.

The database is created without any table inside.

On the left pane under created database, click on new, to create new table.
Enter table name and add required columns and their datatypes.

To check the table structure click on structure tab.

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

Click “GO” to run your query.

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
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
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.

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

VIDEO TUTORIAL
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.

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

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

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

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

Change The following sections to targeted framework version.

In this case am targeting .NET Framework version 4.5.2

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

Click Okay When you are prompted to close open document.

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

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
How To Connect To MySql Database – Part 4 – Check Connection [XAMPP]
Check if database connection is established.
VIDEO TUTORIAL
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
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
How To Insert TextBox Text, Value, Data Into MySql Database – Part 1
The values from textboxes are inserted to database varchar columns.

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

VIDEO TUTORIAL
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
How To Insert Radio Button Values, Data Into MySql Database
Radio button values are inserted to database as varchar.

VIDEO TUTORIAL
How To Insert Checkbox Value, Data Into Database Using C#
CheckBox values are saved in tables varchar column.

VIDEO TUTORIAL
How To Insert Combobox Selected Item, Value Into Mysql In C#
Selected value from dropdown is inserted to tables varchar column.

VIDEO TUTORIAL
How To Save Or Insert Image Into Mysql Database In C#
Image from picturebox is inserted to large BLOB column.

VIDEO TUTORIAL
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; }

VIDEO TUTORIAL
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.

C# SOURCE CODE
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
VIDEO TUTORIAL
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
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
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
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
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
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

To Download “Move Line Extension Using Visual Studio 2010” :
Step 1. Go Tools

Step 2. Choose Extension Manager.

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

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

Step 5. Then Click Download.

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

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

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
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
How To Get Datagridview Currently Selected Row Index On Row click C#
Selected row has a unique index starting from 0.
VIDEO TUTORIAL
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 } }

VIDEO TUTORIAL
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 } }

VIDEO TUTORIAL
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 } }

VIDEO TUTORIAL
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 } }

VIDEO TUTORIAL
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 } }

VIDEO TUTORIAL
How To clear Or Reset a combobox On Button Click In C#
Clearing combobox on button click.

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 Radio Button On Button Click In C#
Resetting all radio buttons on button click.

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 Check Box On Button Click In C#
Unchecking all checkboxes on button click.

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 Text Boxes On Button Click In C#
Clearing all textbox values on button click. Empty values are assigned to Textbox in this scenario.

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 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.

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 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
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”.


VIDEO TUTORIAL
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
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.

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
How To Refresh Datagridview Rows After Change In MySql C#
Reloading the rows after any database change.

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
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.

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
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.

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