Connect your login page with a SQL Server database in ASP.NET Web Forms (C#)

✅ Step-by-Step: Login with SQL Server Database


🔹 1. Create a Database Table

In SQL Server, create a table to store login credentials:

sqlCopyEditCREATE TABLE AdminLogin (
    ID INT PRIMARY KEY IDENTITY,
    Username NVARCHAR(50),
    Password NVARCHAR(50) -- In real apps, use hashed passwords
);

📌 Insert a sample record:

sqlCopyEditINSERT INTO AdminLogin (Username, Password)
VALUES ('admin', '123456');

🔹 2. Add Connection String in Web.config

In your ASP.NET project’s Web.config, add this inside <configuration>:

xmlCopyEdit<connectionStrings>
  <add name="conns" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

📌 Replace YourDatabaseName with your actual DB name.


🔹 3. Update Your Login Page Code

Replace the dummy check in your btnLogin_Click with actual database validation:

csharpCopyEditusing System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class admin_Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) { }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string username = txtUsername.Text.Trim();
        string password = txtPassword.Text.Trim();

        string connStr = ConfigurationManager.ConnectionStrings["conns"].ConnectionString;

        using (SqlConnection conn = new SqlConnection(connStr))
        {
            string query = "SELECT COUNT(*) FROM AdminLogin WHERE Username = @Username AND Password = @Password";
            SqlCommand cmd = new SqlCommand(query, conn);
            cmd.Parameters.AddWithValue("@Username", username);
            cmd.Parameters.AddWithValue("@Password", password);

            conn.Open();
            int count = Convert.ToInt32(cmd.ExecuteScalar());

            if (count == 1)
            {
                lblMessage.Text = "Login successful!";
                lblMessage.CssClass = "text-success";
                Response.Redirect("Dashboard.aspx");
            }
            else
            {
                lblMessage.Text = "Invalid username or password!";
                lblMessage.CssClass = "text-danger";
            }
        }
    }
}

🔐 Optional Security Recommendations

  • ✅ Use hashed passwords (e.g., SHA256 or bcrypt) instead of plain text
  • ✅ Always use parameterized queries (as shown) to prevent SQL Injection
  • ✅ Manage sessions after login for secure access

🧪 Testing Tips

  • Make sure the database table and data exist
  • Double-check the connection string in Web.config
  • Test with correct and incorrect credentials

Leave a Reply

Your email address will not be published. Required fields are marked *