Choose a location:
posted 3/10/2009 by Vijendra Shakya
Here we discuss login in ASP.NET,this is specially help to that user’s which is new in ASP.NET.Login is the basic thing for any application. In login we use the ADO.NET Object such as SqlConnection,SqlCommend and SqlParameter.Suppose we have a table User and user table contains the column UserId, UserName, Password. We create a page with name Login.aspx and we design your login page in following way:
<table> <tr> <td colspan="2"> <asp:Label ID="lblMessage" runat="server"></asp:Label> </td> </tr> <tr> <td> User Name: </td> <td> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Password: </td> <td> <asp:TextBox ID="txtPwd" runat="server" TextMode="Passowrd"> </asp:TextBox> </td> </tr> <tr> <td colspan="2"><asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_OnClick" /> </td> </tr> </table>
Write the Following code on the login button click event on the .cs side as follows:
protected void btnLogin_OnClick(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Your Connection String"); string commandText = "Select count(*) from user where userName='" + txtName.Text + "'and password ='" + txtPwd.Text + "'"; SqlCommand com = new SqlCommand(commandText, con); com.CommandType = CommandType.Text; con.Open(); //ExecuteScalar execute the query and returns the first column of the //first row in the result set int cnt = (int)com.ExecuteScalar(); if (cnt > 0) { Response.Redirect("default.aspx"); } else { lblMessage.Text = "<b>Your UserName or Password is not correct</b>"; }con.Close(); }
What kind of email newsletter would you prefer to receive from CodeAsp.Net? 18