Here in this article, I will show you how to create a login form in C# and connect with SQL Server database in 4 steps.
Step 1: Open Sql Server, 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,
Step 2: In following pic is shown SQL Server 2018 Database Details. and you see the “usr” and “pwd” columns. You use only these three passwords for this login form.
Step 3: Now lets open Visual Studio, then start a new Windows Form Application and give any name you want.
Form Design:
Step 4: This is the coding part of this application below:
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 | 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 System.Data.SqlClient; namespace cce_login_form_with_sql { public partial class Form1 : Form { SqlConnection con; SqlCommand cmd; SqlDataReader dr; public Form1() { InitializeComponent(); con = new SqlConnection("server=DESKTOP-cce\\SQLEXPRESS; Initial Catalog=dbLogin;Integrated Security=SSPI"); } private void button1_Click(object sender, EventArgs e) { string user = txtUser.Text; string pass = txtPass.Text; cmd = new SqlCommand(); 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(); } 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.
This helped a lot, thank you so much. I made a minor error with the query but this put me in the right direction. Thanks again 🙂