Lets assume that we have a Login Form such as:
In the above figure, two Labels, two TextBoxes and one Button is used. First, we need to set the following control's properties:
After setting above properties, click on the Submit button and add the following code in the codebehind(.cs or .vb) file:
VB
In the above figure, two Labels, two TextBoxes and one Button is used. First, we need to set the following control's properties:
Controls | Properties | |
---|---|---|
Label1 | ID | User |
Text | User Name | |
Label2 | ID | Pass |
Text | Password | |
TextBox1 | ID | UserName |
TextMode | SingleLine | |
TextBox2 | ID | Password |
TextMode | Password | |
Button1 | ID | Submit |
Text | Submit |
After setting above properties, click on the Submit button and add the following code in the codebehind(.cs or .vb) file:
C#
using System.Data; using System.Data.SqlClient; namespace Student { public partial class LoginForm : System.Web.UI.Page { protected void Submit_Click(object sender, EventArgs e) {
SqlConnection connection = new SqlConnection("server=myDB; uid=sa;
connection.Open();pwd=password; database=master"); String User = UserName.Text; String Pass = Password.Text; SqlCommand command = new SqlCommand("select count(*) from Login_Form where UserName='" + User + "' and Password='" + Pass + "'", connection); SqlDataReader dataReader = command.ExecuteReader(); while (dataReader.Read()) { if (dataReader.GetValue(0).ToString() == "1") { Response.Redirect("Welcome.aspx"); } else { Response.Write("<script>alert('Invalid UserName/Password');</script>"); } } } } } |
VB
Imports System.Data Imports System.Data.SqlClient Partial Public Class LoginForm Inherits System.Web.UI.Page Protected Sub Submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Submit.Click
Dim connection As SqlConnection = New SqlConnection("server=myDB; uid=sa;
pwd=password;database=master") connection.Open() Dim User As String = UserName.Text Dim Pass As String = Password.Text Dim command As SqlCommand = New SqlCommand("select count(*)from Login_Form where UserName='" + User + "' and Password='" + Pass + "'", connection) Dim dataReader As SqlDataReader = command.ExecuteReader() While (dataReader.Read()) If (dataReader.GetValue(0).ToString() = "1") Then Response.Redirect("Welcome.aspx") Else Response.Write("<script>alert('Invalid UserName/Password');</script>") End If End While End Sub End Class |
If User Name and Password both matches with the User Name and Password that are stored in the database, then 'Welcome.aspx' page would be opened. If User Name and Password both or any one of them does not match, then it would show an error message.