Login Form With SQL In C#

Introduction

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 in visual studio

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.

add connection in visual studio

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

Example. Here write the following code.

public void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=USER;Initial Catalog=admin;Integrated Security=True"); // Making a database connection
    SqlDataAdapter sda = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE username='" + textBox1.Text + "' AND password='" + textBox2.Text + "'", con);
    /* In the above line, the program is selecting the whole data from the table and matching it with the username and password provided by the user. */
    DataTable dt = new DataTable(); // Creating a virtual table
    sda.Fill(dt);
    if (dt.Rows[0][0].ToString() == "1")
    {
        /* I have made a new page called the home page. If the user is successfully authenticated, then the form will be moved to the next form. */
        this.Hide();
        new home().Show();
    }
    else
    {
        MessageBox.Show("Invalid username or password");
    }
}

Step 10. Don't forget to import its library file.

using System.Data.SqlClient;

After this, just debug your code.

library file

I hope you have gotten all this. Thank you.


Similar Articles