Here in this article, I will show you how to create a login form in C# and connect with MySql in 4 steps.
Step 1:
Add MySql Reference to C# Window Form Project
Step 2: Open MySql, click on a New Database. Give database name as “dbLogin” and create a Table in database, You can give any name what you want, here I named it “tblUser” . There are three columns in the table that name are “id“, “usr” and “pwd” like the following,
In following pic is shown MySql Database Details. and you see the “usr” and “pwd” columns. You use only two passwords for this login form.
MySql Database
Step 3: Now lets open Visual Studio, then start a new Windows Form Application and give any name you want.
Step 4:
Source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data; using MySql.Data.MySqlClient; namespace cce_login_form_mysql { public partial class Form1 : Form { MySqlConnection con; MySqlCommand cmd; MySqlDataReader dr; public Form1() { InitializeComponent(); con = new MySqlConnection("Server=localhost;Database=dbLogin;user=cce;Pwd=123123;SslMode=none"); //Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword; } private void Form1_Load(object sender, EventArgs e) { this.Text = "www.csharp-console-examples.com"; } private void button1_Click(object sender, EventArgs e) //Log In Button { string user = txtUser.Text; string pass = txtPass.Text; cmd = new MySqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandText = "SELECT * FROM tblUser where usr='" + txtUser.Text + "' AND pwd='" + txtPass.Text + "'"; dr = cmd.ExecuteReader(); if (dr.Read()) { MessageBox.Show("Login sucess Welcome to Homepage https://csharp-console-examples.com"); } else { MessageBox.Show("Invalid Login please check username and password"); } con.Close(); } //Exit Button private void button2_Click(object sender, EventArgs e) { Application.Exit(); } } } |
Output:
**The conventional way of any login form will contain password displayed in a special character which is for security purposes. To bring that concept into your login form, select the Properties option of TextBox in which you could find the option Password Char where you can give your desired special character (in my case, I have used * asterisk). By making this change, if you run your application, it will display only the special symbol when you enter a password.