Login Form With SQL in C#

The database I will use is MySQL. I will tell you how to connect a database and how to make a simple login form. To do this, just use the following simple procedure.

Note: Now you can read it on my blog.I have updated this article on my personal blog here.

Step 1

Open Visual Studio and create a new Windows Forms project.

Step 2

Make a simple form having the 2 text fields username and password and a login button.

Step 3

Now go to the menu bar, select the view option and there you can see “Server Explorer”. Just click on that and the Server Explorer will be opened.

server explorer

Step 4

Now add your connection. There you can see an option of server name. Here you need to write the name of your server, the same as in your SQL. When you provide the server name, just go to the select option, there you'll see the entire database name that you have made. You can create your new database too.

type server name

Step 5

It'll ask for permission and click Yes.

Step 6

Now you'll be able to see your DB in your Server Explorer tab.

Step 7

Click on it. There you'll see tables. To create a new one, right-click on that and add a new table.

add new table

Step 8

Now you need to add some data in it. To do so just follow the figure:

add data

Step 9

Now your database is created, we only need to connect it with our form. To do this open your form and double-click on the button you have made. It"ll take you to the code of that button. Here write the following code:
  1. public void button1_Click(object sender, EventArgs e)  
  2. {  
  3.    SqlConnection con = new SqlConnection(@"Data Source=USER;Initial Catalog=admin;Integrated Security=True"); // making connection   
  4.    SqlDataAdapter sda = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE username='"+ textBox1.Text +"' AND password='"+ textBox2.Text +"'",con);  
  5.         /* in above line the program is selecting the whole data from table and the matching it with the user name and password provided by user. */  
  6.    DataTable dt = new DataTable(); //this is creating a virtual table  
  7.    sda.Fill(dt);  
  8.    if (dt.Rows[0][0].ToString() == "1")  
  9.    {  
  10.       /* I have made a new page called home page. If the user is successfully authenticated then the form will be moved to the next form */   
  11.       this.Hide();  
  12.       new home().Show();  
  13.    }  
  14.    else  
  15.    MessageBox.Show("Invalid username or password");  
  17. }  
Step 10

Don't forget to import it's library file.
  1. using System.Data.SqlClient;  
After this just debug your code.

library file

I hope you have gotten all this. Thank you.


Similar Articles