Java Login Form

Java Login Form + And Show Another Form

________________________________________________________

In this java Tutorial we will see How To Create A Login Form With Mysql Database And Close The Login Window And Open Another JFrame In Java NetBeans .


Part 1 


Part 2


Project Source Code:

package MyPackage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class Java_Login_Form extends javax.swing.JFrame {

    /**
     * Creates new form Java_Login_Form
     */
    public Java_Login_Form() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField_Username = new javax.swing.JTextField();
        jPasswordField_Password = new javax.swing.JPasswordField();
        jButton_Login = new javax.swing.JButton();
        jButton_Cancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/lock 2.png"))); // NOI18N

        jLabel2.setText("Username : ");

        jLabel3.setText("Password :");

        jButton_Login.setText("Login");
        jButton_Login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_LoginActionPerformed(evt);
            }
        });

        jButton_Cancel.setText("Cancel");
        jButton_Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel1)
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField_Username)
                            .addComponent(jPasswordField_Password, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)))
                    .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(105, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(263, 263, 263)
                    .addComponent(jButton_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(265, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextField_Username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(69, 69, 69)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jPasswordField_Password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(34, 34, 34)
                        .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(38, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(210, Short.MAX_VALUE)
                    .addComponent(jButton_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(36, 36, 36)))
        );

        pack();
    }// </editor-fold>                        

    private void jButton_CancelActionPerformed(java.awt.event.ActionEvent evt) {                                               
        System.exit(0);
    }                                              

    private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {                                              
        Connection connection;
        PreparedStatement ps;
       
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
            ps = connection.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?");
            ps.setString(1, jTextField_Username.getText());
            ps.setString(2, String.valueOf(jPasswordField_Password.getPassword()));
            ResultSet rs = ps.executeQuery();
            
            if(rs.next())
            {
                setVisible(false);
                MainForm mf = new MainForm();
                mf.setVisible(true);
            }else{
                JOptionPane.showMessageDialog(this, "Username Or Password Are Invalid");
            }
        } catch (SQLException ex) {
            Logger.getLogger(Java_Login_Form.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                             

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Java_Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Java_Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Java_Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Java_Login_Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Java_Login_Form().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton_Cancel;
    private javax.swing.JButton jButton_Login;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField jPasswordField_Password;
    private javax.swing.JTextField jTextField_Username;
    // End of variables declaration                   
}


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

java login window


Java Confirmation Message

Java Show Confirm Message

________________________________________________________

In this java Tutorial we will see How To Show Message To Confirm Something Like Delete, Update .....  In Java NetBeans .




Project Source Code:

package java_tutorials;

import javax.swing.JOptionPane;

public class Java_Confirmation_Message extends javax.swing.JFrame {

    /**
     * Creates new form Java_Confirmation_Message
     */
    public Java_Confirmation_Message() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Confirm");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTextField1.setText("Text Message Here LLLLQSLQLSLQLQQQ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(161, 161, 161))
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(49, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(80, 80, 80)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(71, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                      

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       
        int YesOrNo = JOptionPane.showConfirmDialog(null,"Do You Want To Clear TextField","Clear TextField", JOptionPane.YES_NO_OPTION);
        if(YesOrNo == 0)
        {
            jTextField1.setText("Yes");
        }else{
            jTextField1.setText("No");   
        }
        
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Java_Confirmation_Message.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Java_Confirmation_Message.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Java_Confirmation_Message.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Java_Confirmation_Message.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Java_Confirmation_Message().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                  
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                
}


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



Java Show Confirm Message

Java - Close A JFrame And Open Another

Java - How To Hide A JFrame And Show Another 

________________________________________________________

In this Java Tutorial we will see How To Close A Window And Open An Another In JButton Click using Java NetBeans .




Project Source Code:

package MyPackage;

public class Java_Open_New_Frame extends javax.swing.JFrame {

    /**
     * Creates new form Java_Open_New_Frame
     */
    public Java_Open_New_Frame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        jButton_Open = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton_Open.setText("Open New Window");
        jButton_Open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_OpenActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(98, 98, 98)
                .addComponent(jButton_Open, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(138, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(119, 119, 119)
                .addComponent(jButton_Open)
                .addContainerGap(158, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                      

    private void jButton_OpenActionPerformed(java.awt.event.ActionEvent evt) {                                          
     

        setVisible(false);        Java_Login_Form form = new Java_Login_Form();        form.setVisible(true);

     
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Java_Open_New_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Java_Open_New_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Java_Open_New_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Java_Open_New_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Java_Open_New_Frame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                  
    private javax.swing.JButton jButton_Open;
    // End of variables declaration                
}


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

java hide and show jframe



C# Text Style

How To Style Text In C#

                                                                                                                                         

In This C# Tutorial We Will See How To Change A Label Font Name, Size, Color, Style Using CSharp Programming Language
                               

                                                                            Part 1

Part 2

Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Text_Style : Form
    {
        public Text_Style()
        {
            InitializeComponent();
        }

        private void Text_Style_Load(object sender, EventArgs e)
        {
            foreach(FontFamily font in FontFamily.Families)
            {
                comboBox_Fonts.Items.Add(font.Name.ToString());
            }
         }

        private void comboBox_Fonts_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                lbl_text.Font = new Font(comboBox_Fonts.Text, lbl_text.Font.Size);
            }
            catch { }
        }

        private void comboBox_SIZE_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                lbl_text.Font = new Font(lbl_text.Font.FontFamily, float.Parse(comboBox_SIZE.SelectedItem.ToString()));
            }
            catch
            {

            }
        }

        private void BTN_COLOR_Click(object sender, EventArgs e)
        {
            DialogResult colors = colorDialog1.ShowDialog();

            if(colors == DialogResult.OK)
            {
                lbl_text.ForeColor = colorDialog1.Color;
            }
        }

        private void RD_REGULAR_CheckedChanged(object sender, EventArgs e)
        {
            lbl_text.Font = new Font(lbl_text.Font.FontFamily, lbl_text.Font.Size, FontStyle.Regular);
        }

        private void RD_BOLD_CheckedChanged(object sender, EventArgs e)
        {
            lbl_text.Font = new Font(lbl_text.Font.FontFamily, lbl_text.Font.Size, FontStyle.Bold);
        }

        private void RD_UNDERLINE_CheckedChanged(object sender, EventArgs e)
        {
            lbl_text.Font = new Font(lbl_text.Font.FontFamily, lbl_text.Font.Size, FontStyle.Underline);
        }

        private void RD_STRIKEOUT_CheckedChanged(object sender, EventArgs e)
        {
            lbl_text.Font = new Font(lbl_text.Font.FontFamily, lbl_text.Font.Size, FontStyle.Strikeout);
        }
    }
}

=> OutPut :


c# text font style

C# And MySQL - Search Using TextChanged Event

C# - How To Use TextChanged To Search And Display Data In DatagridView

                                                                                                                                         

In This C# Tutorial We Will See How To Search Data In MySQL On The TextChanged Event And Show This Data On Datagridview Using CSharp Programming Language And MySQL Database.
-

Source Code :

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Csharp_And_MySQL
{
    public partial class TextChanged_Search : Form
    {
        public TextChanged_Search()
        {
            InitializeComponent();
        }

        MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='test_db';username=root;password=");

        private void TextChanged_Search_Load(object sender, EventArgs e)
        {
            searchData("");
        }

        public void searchData(string valueToFind)
        {

            string searchQuery = "SELECT * FROM users WHERE CONCAT(fname,lname) LIKE '%"+valueToFind+"%'";
            MySqlDataAdapter adapter = new MySqlDataAdapter(searchQuery, connection);
            DataTable table = new DataTable();
            adapter.Fill(table);
            dataGridView_Data.DataSource = table;

        }

        private void textBox1_Search_TextChanged(object sender, EventArgs e)
        {
            searchData(textBox1_Search.Text);
        }
     
    }
}

=> OutPut :


c# textchanged

C# & MySQL - Insert Update Delete Search Display


In This C# Tutorial We Will See How To Insert Update Delete Search And Display Data From Database Using CSharp Programming Language And MySQL Database.


                                                                          Part 1

Part 2

Source Code :

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Csharp_And_MySQL
{
    public partial class Insert_Update_Delete_Search_Display : Form
    {
        public Insert_Update_Delete_Search_Display()
        {
            InitializeComponent();
        }

        MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='test_db';username=root;password=");
        MySqlCommand command;
        private void Insert_Update_Delete_Search_Display_Load(object sender, EventArgs e)
        {
            populateDGV();
        }

        public void populateDGV()
        {
            // populate the datagridview
            string selectQuery = "SELECT * FROM users";
            DataTable table = new DataTable();
            MySqlDataAdapter adapter = new MySqlDataAdapter(selectQuery, connection);
            adapter.Fill(table);
            dataGridView_USERS.DataSource = table;
        }

        private void dataGridView_USERS_MouseClick(object sender, MouseEventArgs e)
        {
            textBoxID.Text = dataGridView_USERS.CurrentRow.Cells[0].Value.ToString();
            textBoxFName.Text = dataGridView_USERS.CurrentRow.Cells[1].Value.ToString();
            textBoxLName.Text = dataGridView_USERS.CurrentRow.Cells[2].Value.ToString();
            textBoxAge.Text = dataGridView_USERS.CurrentRow.Cells[3].Value.ToString();
        }

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

        public void closeConnection()
        {
            if(connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }

        public void executeMyQuery(string query)
        {
            try
            {
                openConnection();
                command = new MySqlCommand(query,connection);

                if(command.ExecuteNonQuery() == 1)
                {
                    MessageBox.Show("Query Executed");
                }

                else
                {
                    MessageBox.Show("Query Not Executed");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }finally
            {
                closeConnection();
            }
        }

        private void BTN_INSERT_Click(object sender, EventArgs e)
        {
            string insertQuery = "INSERT INTO users(fname, lname, age) VALUES('" + textBoxFName.Text + "','" + textBoxLName.Text + "'," + textBoxAge.Text +")";
            executeMyQuery(insertQuery);
            populateDGV();
        }

        private void BTN_UPDATE_Click(object sender, EventArgs e)
        {
            string updateQuery = "UPDATE users SET fname='"+textBoxFName.Text+"',lname='"+textBoxLName.Text+"',age="+textBoxAge.Text+" WHERE id ="+int.Parse(textBoxID.Text);
            executeMyQuery(updateQuery);
            populateDGV();
        }

        private void BTN_DELETE_Click(object sender, EventArgs e)
        {
            string deleteQuery = "DELETE FROM users WHERE id = "+int.Parse(textBoxID.Text);
            executeMyQuery(deleteQuery);
            populateDGV();
        }

        private void BTN_SEARCH_Click(object sender, EventArgs e)
        {
            MySqlDataReader mdr;
            string select = "SELECT * FROM users WHERE id = " + textBoxID.Text;
            command = new MySqlCommand(select,connection);
            openConnection();
            mdr = command.ExecuteReader();

            if(mdr.Read())
            {
                textBoxFName.Text = mdr.GetString("fname");
                textBoxLName.Text = mdr.GetString("lname");
                textBoxAge.Text = mdr.GetInt32("age").ToString();
            }
            else
            {
                MessageBox.Show("User Not Found");
            }

            closeConnection();
        }
     
    }
}

=> OutPut :


C# And MySQL Insert Update Delete Search Display

C# - Using BindingManagerBase

C# How To Use BindingManagerBase And MySql CommandBuilder


In This C# Tutorial We Will See How To Use BindingManagerBase To Insert Update Delete Search And Navigate Data From Database Using CSharp Programming Language And MySQL Database.


                                                                          Part 1

Part 2

Source Code :

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Csharp_And_MySQL
{
    public partial class Using_DataBindings : Form
    {
        public Using_DataBindings()
        {
            InitializeComponent();
        }

        MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog ='test_db';username=root;password=");
        MySqlCommand command;
        MySqlDataAdapter adapter;
        DataTable table = new DataTable();
        BindingManagerBase managerBase;
        MySqlCommandBuilder builder;

        private void Using_DataBindings_Load(object sender, EventArgs e)
        {
            string query = "SELECT * FROM users";
            command = new MySqlCommand(query, connection);
            adapter = new MySqlDataAdapter(command);
            adapter.Fill(table);
            dataGridView1.DataSource = table;
            textBoxID.DataBindings.Add("text",table,"id");
            textBoxFName.DataBindings.Add("text", table, "fname");
            textBoxLName.DataBindings.Add("text", table, "lname");
            textBoxAge.DataBindings.Add("text", table, "age");

            managerBase = this.BindingContext[table];
        }

        private void BTN_FIRST_Click(object sender, EventArgs e)
        {
            managerBase.Position = 0;
        }

        private void BTN_NEXT_Click(object sender, EventArgs e)
        {
            managerBase.Position += 1;
        }

        private void BTN_PREVIOUS_Click(object sender, EventArgs e)
        {
            managerBase.Position -= 1;
        }

        private void BTN_LAST_Click(object sender, EventArgs e)
        {
            managerBase.Position = managerBase.Count;
        }

        private void BTN_NEW_Click(object sender, EventArgs e)
        {
            managerBase.AddNew();
        }

        private void BTN_INSERT_Click(object sender, EventArgs e)
        {
            managerBase.EndCurrentEdit();
            builder = new MySqlCommandBuilder(adapter);
            adapter.Update(table);
            MessageBox.Show("New User Added","New User",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        private void BTN_UPDATE_Click(object sender, EventArgs e)
        {
            managerBase.EndCurrentEdit();
            builder = new MySqlCommandBuilder(adapter);
            adapter.Update(table);
            MessageBox.Show("User Data Updated", "Edit User", MessageBoxButtons.OK, MessageBoxIcon.Information);
     
        }

        private void BTN_DELETE_Click(object sender, EventArgs e)
        {
            managerBase.RemoveAt(managerBase.Position);
            builder = new MySqlCommandBuilder(adapter);
            adapter.Update(table);
            MessageBox.Show("User Deleted", "Remove User", MessageBoxButtons.OK, MessageBoxIcon.Information);
     
        }
    }
}

=> OutPut :


C# Using BindingManagerBase

C# Difference Between Two Dates

C# Timespan Difference Between Two Datetime

                                                                                                                                         

In This C# Tutorial We Will See How To Get The Difference Between Two DateTimePicker In
- Days.
- Hours.
- Minutes.
- Seconds
- Millisconds.
 Using CSharp Programming Language

Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class difference_between_two_dates : Form
    {
        public difference_between_two_dates()
        {
            InitializeComponent();
        }

        private void BTN_CALC_Click(object sender, EventArgs e)
        {
            DateTime date1 = dateTimePicker1.Value;
            DateTime date2 = dateTimePicker2.Value;

            TimeSpan difference = date2 - date1;
            lbl_Days.Text = "Days: " + difference.TotalDays.ToString();
            lblH.Text = "Hours: " + difference.TotalHours.ToString();
            lblM.Text = "Minutes: " + difference.TotalMinutes.ToString();
            lblS.Text = "Seconds: " + difference.TotalSeconds.ToString();
            lblMS.Text = "Milliseconds: " + difference.TotalMilliseconds.ToString();
        }
    }
}

=> OutPut :


C# Difference Between Two DateTime

C# Update ListBox Item

How To Update ListBox Selected Item In C#

                                                                                                                                         

In This C# Tutorial We Will See How To Display Selected Listbox Item Into TextBox And Edit It With A New Value From The TextBox Using CSharp Programming Language And .

Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class ListBox_Form : Form
    {
        public ListBox_Form()
        {
            InitializeComponent();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = listBox1.SelectedItem.ToString();
            }catch
            {

            }      
        }

        private void BTN_UPDATE_Click(object sender, EventArgs e)
        {
            int index = listBox1.SelectedIndex;
            listBox1.Items.RemoveAt(index);
            listBox1.Items.Insert(index, textBox1.Text);
        }
    }
}

=> OutPut :


c# edit listbox selected item

C# Confirmation Message

C# MessageBox Confirm Yes No

                                                                                                                                         

In This C# Tutorial We Will See How To Use MessageBox To Confirm Delete With Yes And No Choice Using CSharp Programming Language.
-

Source Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Confirmation_Message : Form
    {
        public Confirmation_Message()
        {
            InitializeComponent();
        }

        private void Confirmation_Message_Load(object sender, EventArgs e)
        {
            DataTable table = new DataTable();
            table.Columns.Add("ID");
            table.Columns.Add("First Name");
            table.Columns.Add("Last Name");
            table.Columns.Add("Age");

            table.Rows.Add(1, "First A", "Last A", 10);
            table.Rows.Add(2, "First B", "Last B", 20);
            table.Rows.Add(3, "First C", "Last C", 30);
            table.Rows.Add(4, "First D", "Last D", 40);
            table.Rows.Add(5, "First E", "Last E", 50);
            table.Rows.Add(6, "First F", "Last F", 60);
            table.Rows.Add(7, "First G", "Last G", 70);
            table.Rows.Add(8, "First H", "Last H", 80);

            dataGridView1.DataSource = table;
        }

        private void BTN_REMOVE_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("Do You Want To Remove This Row","Remove Row",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
            }
            
            else
            {
                MessageBox.Show("Row Not Removed","Remove Row", MessageBoxButtons.OK,MessageBoxIcon.Information);
            }

        }
    }
}

=> OutPut :

C# Confirmation Message Box