Anda di halaman 1dari 14

DaniWeb Forum Index > Software Development > C#

Simple ASP.Net Login Page using C# C# RSS

Please support our C# advertiser: Intel Parallel Studio Home

Ads by Google XP Themes Windows Theme Computer Theme Examples in C

These search terms have been highlighted: login page in asp.net (Clear)

1 2 > Last »

• Paladine
Master Poster

Simple ASP.Net Login Page using C#


Offline
Join Date: Feb 2003
Posts: 793
Reputation:
Solved Threads: 26 • You need to join our community in order to
build your list of favorite forums. You can
visit the forum index for a listing of all
forums.

May 23rd, 2005 0 #1

Simple ASP.NET Login Page using C# ( ASP.NET 1.0 & 1.1 ONLY!!! NOT 2.0)

This is just a small demonstration to show how easy one can "port" the code from my
previous tutorials ( Updated: Simple ASP.Net Login Page & ASP.Net Login
Page with SQL & ASP.Net Registration Page ) over to another programming
language in the .NET environment. In this example I chose to use C#.

So for all considerations this tutorial is an exact duplicate of the Updated: Simple
ASP.NET Login Page using VB.NET that I did previously, but using SQL instead of
Access for the DB

RELATED FORUM FEATURES

1. Create a Login Webform (HTML/ASP.NET) C# Forum

- Include any control validation you feel necessary. Software Development Forum

C# Upvoted Threads (61)


NorthCSharp.aspx
C# Solved Threads (1,364)

(Toggle Plain Text) Help with Code Tags C# News Stories (2)

C# Code Snippets (133)


<%@ Page language="c#" Codebehind=" Login .aspx.cs" AutoEventWireup="false" Inherits="NorthCSharp.Web
AutoEventWireup="false" Inherits="NorthCSharp.WebForm1" %> C# Forum Search
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>WebForm1</title> LATEST C# POSTS
<meta name="GENERATOR" content="Microsoft Visual Studio .NET
7.1">  Today's Posts
<meta name="CODE_LANGUAGE" content="C#">  C#
<meta name="vs_defaultClientScript" content="JavaScript">
 Software Development
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">  All Forums
<!-- <summary>  Unanswered Threads
||||| Style Sheet |||||
</summary>
--><link title="standard" href="Styles.css" type="text/css"
rel="stylesheet">
</head>
<body>
<!-- ||||| Login Form ||||| -->
<form id="frmlogin" method="post" runat="server">
<table id="mainTable" border="0">
<tr>
<td>
<table class="t_border" id="loginTable"
cellspacing="15" cellpadding="0">
<tr>
<td><b> Login : </b>
</td>
<td><asp:textbox id="txtUserName" runat="server"
width="160px"></asp:textbox><asp:requiredfieldvalidator
id="rvUserValidator" runat="server" controltovalidate="txtUserName"
errormessage="You must supply a Username!"

display="None"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td><b>Password: </b>
</td>
<td><asp:textbox id="txtPassword" runat="server"
width="160px"
textmode="Password"></asp:textbox><asp:requiredfieldvalidator
id="rvPasswordValidator" runat="server" controltovalidate="txtPassword"
errormessage="Empty Passwords not accepted"

display="None"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td align="center" colspan="2"><asp:button
id="cmdSubmit" runat="server" text="Submit"
borderstyle="Solid"></asp:button></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="messageDisplay">
<tr>
<td><asp:validationsummary
id="Validationsummary1" runat="server" width="472px"
displaymode="BulletList"></asp:validationsummary></td>
</tr>
</table>
<!--<asp:hyperlink id="hl_Register"
runat="server" navigateurl="Register.aspx" font-size="X-Small"
height="8px" width="209px" font-names="MS
Reference Sans Serif">New User?...Register Here!</asp:hyperlink>-->
</td>
</tr>
</table>
</form>
<asp:label id="lblMessage" runat="server" width="288px" font-
bold="True" font-italic="True"
font-size="Medium" forecolor="#C00000"></asp:label>
<asp:label id="lblMessage2" runat="server" width="288px" font-
bold="True" font-italic="True"
font-size="Medium" forecolor="#C00000"></asp:label>
<!-- ||||| End of Form ||||| -->
</body>
</html>

2. Create the Code Behind (C#)


- One thing to note here, you use the keyword using instead of import to "import/include"
the namespaces you require for security, data access, etc.
- Also note how clean and short the code structure is when comparing VB.Net to C#. Now
in my opinion, I love VB.Net far more than C# or C++, as I find it more intuitive, but
each to his own.
NorthCSharp.aspx.cs

(Toggle Plain Text) Help with Code Tags

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
// <summmary>
// What has been added for Login Page
// for this application to function
// </summary>
using System.Web.Security;
using System.Data.SqlClient;
using System.Configuration;

namespace NorthCSharp
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtUserName;
protected System.Web.UI.WebControls.RequiredFieldValidator
rvUserValidator;
protected System.Web.UI.WebControls.TextBox txtPassword;
protected System.Web.UI.WebControls.RequiredFieldValidator
rvPasswordValidator;
protected System.Web.UI.WebControls.Button cmdSubmit;
protected System.Web.UI.WebControls.ValidationSummary
Validationsummary1;
protected System.Web.UI.WebControls.Label lblMessage;
protected System.Web.UI.WebControls.Label lblMessage2;

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
}

#region Web Form Designer generated code


override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdSubmit.Click += new System.EventHandler
(this.cmdSubmit_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void cmdSubmit_Click(object sender, System.EventArgs e)


{
if ( Page .IsValid)
{
if (DBConnection(txtUserName.Text.Trim(),
txtPassword.Text.Trim()))
{
FormsAuthentication.RedirectFromLoginPage
(txtUserName.Text, false);
}
else
{
lblMessage.Text = "Invalid Login , please try again!";
}
}

}
private bool DBConnection(string txtUser, string txtPass)
{
SqlConnection myConn = new SqlConnection
(ConfigurationSettings.AppSettings["strConn"]);
SqlCommand myCmd = new SqlCommand("sp_ValidateUser", myConn);
myCmd.CommandType = CommandType.StoredProcedure;

SqlParameter objParam1;
SqlParameter objParam2;
SqlParameter returnParam;

objParam1 = myCmd.Parameters.Add ("@UserName",


SqlDbType.VarChar);
objParam2 = myCmd.Parameters.Add ("@Password",
SqlDbType.VarChar);
returnParam = myCmd.Parameters.Add ("@Num_of_User",
SqlDbType.Int);

objParam1.Direction = ParameterDirection.Input;
objParam2.Direction = ParameterDirection.Input;
returnParam.Direction = ParameterDirection.ReturnValue;

objParam1.Value = txtUser;
objParam2.Value = txtPass;

try
{
if (myConn.State.Equals(ConnectionState.Closed))
{
myConn.Open();
myCmd.ExecuteNonQuery();
}
if ((int)returnParam.Value < 1)
{
lblMessage.Text = "Invalid Login !";
return false;
}
else
{
myConn.Close();
return true;
}
}
catch (Exception ex)
{
lblMessage2.Text = ex + "Error Connecting to the database";
return false;
}

}
}
}

3. Add the following line to the Web.Config file to enable DB access


- Notice that this is no different than the one used in the VB.Net Example
- I have removed my login info from the strConn, don't forget to add yours in place!

Web.Config
(Toggle Plain Text) Help with Code Tags

]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="strConn" value="Network Library=DBMSSOCN;Data
Source=192.168.0.100,1433;database=Northwind;User id=;Password=;"/>
</appSettings>
<system.web>

<!-- DYNAMIC DEBUG COMPILATION


...
...
...

Happy Coding!

Last edited by Paladine; Oct 31st, 2006 at 3:08 am.

Assistant Manager, Pharmacy Informatics


Wordpress Learning Blog
Updated : ASP.Net Login Code


Ads by Google

C Source Code
Be a Software Professional by Choosing a course @ MingleBox.com
MingleBox.com/C_Courses

C++
ForumNokia Developer Conference. Learn from Mobile Experts.KnowMore!
www.Nokiadevcon.in

LogExpert
Windows tail program and logfile analysis for free. www.log-expert.de/

Hiring C++ and QT Experts


Work from Home C++ Programmers w/ QT Background. Great Salary
Career.GlobalWorkforce.com


BeeNarak
Newbie Poster
Offline

Re: Simple ASP.Net Login Page using C#


Jul 12th, 2005
Posts: 8
Reputation:

Join Date: Jul 2005

Solved Threads: 0

0 #2

Hi Paladine,

I have to modify the c# code from the SQL server example to work for AccessDB
but it's doesn't work. Please see my code as below;

C# Syntax (Toggle Plain Text) Help with Code Tags

1. private bool DBConnection(string strUserName, string strPassword)


2. {
3. OleDbConnection MyConn = new
OleDbConnection(ConfigurationSettings.AppSettings["strConn"]);
4. OleDbCommand MyCmd = new OleDbCommand
("sp_ValidateUser", MyConn);
5.
6. MyCmd.CommandType =
CommandType.StoredProcedure;
7.
8. OleDbParameter objParam1, objParam2;
9.
10. objParam1 = MyCmd.Parameters.Add
("@UserName", OleDbType.Char);
11. objParam2 = MyCmd.Parameters.Add
("@Password", OleDbType.Char);
12. //returnParam = MyCmd.Parameters.Add
("@Num_of_User", OleDbType.Integer);
13.
14. objParam1.Direction =
ParameterDirection.Input;
15. objParam2.Direction =
ParameterDirection.Input;
16. //returnParam.Direction =
ParameterDirection.ReturnValue;
17.
18. objParam1.Value = txtUserName.Text;
19. objParam2.Value = txtPassword.Text;
20.
21. try
22. {
23. if(MyConn.State ==
ConnectionState.Closed)
24. {
25. MyConn.Open();
26.
27. }
28.
29. OleDbDataReader objReader;
30. objReader = MyCmd.ExecuteReader
(CommandBehavior.CloseConnection);
31.
32. while(objReader.Read())
33. {
34.
35. if ((string)
objReader.GetValue(0) != "1")
36. {
37.
lblMessage.Text = "Invalid Login !";
38. //return
false;
39. }
40. else
41. {
42.
objReader.Close();
43. return true;
44. }
45.
46. }
47.
48. }
49. catch(Exception ex)
50. {
51. lblMessage2.Text = "Error
Connecting to the database!";
52. //return false;
53. }
54.
55.
56. }

Could you please advise if you have any idea?


Thank you very much,

BeeNarak
• Paladine
Master Poster
Offline

Re: Simple ASP.Net Login Page using C#


Posts: 793
Reputation:

Join Date: Feb 2003

Solved Threads: 26

Jul 12th, 2005 0 #3

I will try my best to help.

Ok What error are you getting? Saying it doesn't work provides me no indication as to
what the problem is.

Why are you converting an int value to a string and comparing it to a string int?

code in question:

C# Syntax (Toggle Plain Text) Help with Code Tags

1. (string)objReader.GetValue(0) != "1"

Should be

C# Syntax (Toggle Plain Text) Help with Code Tags

1. objReader.GetValue(0) = 0

I also may need to see what your stored procedure code looks like.

Assistant Manager, Pharmacy Informatics


Wordpress Learning Blog
Updated : ASP.Net Login Code


BeeNarak
Newbie Poster
Offline

Re: Simple ASP.Net Login Page using C#


Jul 12th, 2005
Posts: 8
Reputation:

Join Date: Jul 2005

Solved Threads: 0

0 #4

Hi Paladine,
Thank you so much for your explanations.

Why are you converting an int value to a string and comparing it to a string int?
- Sorry i'm poor experience about c# programing so some time i've got a mistake. :s

I am just learning ASP.NET and I am trying to build an ASP.Net login page .


Before that i've got an error '(' Login .WebForm1.DBConnection(string, string)' and than i
try to chage '(string)objReader.GetValue(0) != "1"' to 'objReader.GetValue(0) = 0' error is
'Cannot implicitly convert type 'object' to 'bool' and 'The left-hand side of an assignment
must be a variable, property or indexer'
Do you have any idea?

my code as below;

C# Syntax (Toggle Plain Text) Help with Code Tags


1. using System;
2. using System.Collections;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Web;
7. using System.Web.SessionState;
8. using System.Web.UI;
9. using System.Web.UI.WebControls;
10. using System.Web.UI.HtmlControls;
11. using System.Web.Security;
12. using System.Data.OleDb;
13. using System.Configuration;
14.
15. namespace Login
16. {
17. /// <summary>
18. /// Summary description for WebForm1.
19. /// </summary>
20. public class WebForm1 : System.Web.UI. Page
21. {
22. protected System.Web.UI.WebControls.TextBox
txtUserName;
23. protected
System.Web.UI.WebControls.RequiredFieldValidator rvUserValidator;
24. protected System.Web.UI.WebControls.TextBox
txtPassword;
25. protected
System.Web.UI.WebControls.RequiredFieldValidator
rvPasswordValidator;
26. protected System.Web.UI.WebControls.Button
cmdSubmit;
27. protected
System.Web.UI.WebControls.ValidationSummary Validationsummary1;
28. protected System.Web.UI.WebControls.Label
lblMessage2;
29. protected System.Web.UI.WebControls.Label
lblMessage;
30. //protected System.Web.UI.Page.Session;
31.
32. private void Page_Load(object sender,
System.EventArgs e)
33. {
34. // Put user code to initialize the page
here
35. }
36.
37. private bool DBConnection(string strUserName,
string strPassword)
38. {
39. string LoginSQL;
40. OleDbConnection MyConn = new
OleDbConnection(ConfigurationSettings.AppSettings["strConn"]);
41. OleDbCommand MyCmd = new OleDbCommand
("sp_ValidateUser", MyConn);
42.
43. MyCmd.CommandType =
CommandType.StoredProcedure;
44.
45. OleDbParameter objParam1, objParam2;
46.
47. objParam1 = MyCmd.Parameters.Add
("@UserName", OleDbType.Char);
48. objParam2 = MyCmd.Parameters.Add
("@Password", OleDbType.Char);
49. //returnParam = MyCmd.Parameters.Add
("@Num_of_User", OleDbType.Integer);
50.
51. objParam1.Direction =
ParameterDirection.Input;
52. objParam2.Direction =
ParameterDirection.Input;
53. //returnParam.Direction =
ParameterDirection.ReturnValue;
54.
55. objParam1.Value = txtUserName.Text;
56. objParam2.Value = txtPassword.Text;
57.
58. try
59. {
60. if(MyConn.State ==
ConnectionState.Closed)
61. {
62. MyConn.Open();
63.
64. }
65.
66. OleDbDataReader objReader;
67. objReader = MyCmd.ExecuteReader
(CommandBehavior.CloseConnection);
68.
69. while(objReader.Read())
70. {
71.
72. if (objReader.GetValue
(0) = 0)
73. {
74.
lblMessage.Text = "Invalid Login !";
75. //return
false;
76. }
77. else
78. {
79.
objReader.Close();
80. return true;
81. }
82.
83. }
84.
85. }
86. catch(Exception ex)
87. {
88. lblMessage2.Text = "Error
Connecting to the database!";
89. //return false;
90. }
91.
92.
93. }
94.
95.
96. #region Web Form Designer generated code
97. override protected void OnInit(EventArgs e)
98. {
99. //
100. // CODEGEN: This call is required by the
ASP.NET Web Form Designer.
101. //
102. InitializeComponent();
103. base.OnInit(e);
104. }
105.
106. /// <summary>
107. /// Required method for Designer support - do not
modify
108. /// the contents of this method with the code
editor.
109. /// </summary>
110. private void InitializeComponent()
111. {
112. this.cmdSubmit.Click += new
System.EventHandler(this.cmdSubmit_Click);
113. this.Load += new System.EventHandler
(this.Page_Load);
114.
115. }
116. #endregion
117.
118. private void cmdSubmit_Click(object sender,
System.EventArgs e)
119. {
120. if( Page .IsValid) //Meaning the Control
Validation was successful!
121. { //Connect to Database for User
Validation
122. //int intMaxLoginAttempts =
((Int32)Session["Num_of_Tries"]);
123. if(DBConnection
(txtUserName.Text.Trim(), txtPassword.Text.Trim()))
124. {
125. //if(Session
["Logged_IN"].Equals("Yes")) //Use to Validate on other pages in
the application
126. //{
127. //Session
["Logged_IN"].Equals("Yes");
128.
FormsAuthentication.RedirectFromLoginPage
(txtUserName.Text, false); //default.aspx Page !
129.
//Response.Redirect("default.aspx");
130.
//Response.Redirect("../Login.aspx?
ReturnUrl=/default.aspx");
131. //}
132. //lblMessage.Text
= "Success Full";
133.
134. }
135. else
136. { //Credentials are
Invalid
137. lblMessage.Text
= "Sorry! Your login or password is incorrect. \n\n Please log
in again.";
138. //Session
["LoginCount"] = ((Int32)Session["LoginCount"]) + 1;
139. //Response.Redirect
("default.aspx");
140. }
141. /*if(Session
["LoginCount"].Equals(intMaxLoginAttempts))
142. {
143. Response.Redirect
("Denied.aspx");
144. }
145.
146. if(((Int32)Session
["Num_of_Tries"]) > 2)
147. {
148. Response.Redirect
("Denied.aspx");
149. }*/
150.
151. }
152. }
153. }
154. }

Last edited by Paladine; Jul 14th, 2005 at 3:06 am. Reason: Adding code blocks

• Paladine
Master Poster
Offline

Re: Simple ASP.Net Login Page using C#


Posts: 793
Reputation:

Join Date: Feb 2003

Solved Threads: 26
Jul 12th, 2005 0 #5

No worries...

It should be (and please review the code you copied from - i.e the tutorial)

C# Syntax (Toggle Plain Text) Help with Code Tags

1. (int)objReader.GetValue(0) = 0

Assistant Manager, Pharmacy Informatics


Wordpress Learning Blog
Updated : ASP.Net Login Code


BeeNarak
Newbie Poster
Offline

Re: Simple ASP.Net Login Page using C#


Jul 13th, 2005
Posts: 8
Reputation:

Join Date: Jul 2005

Solved Threads: 0

0 #6

Hi Paladine,

Thanks for your explanations. I've to change as your idea from "(objReader.GetValue(0) =
0)" to "(int)objReader.GetValue(0) = 0" as your idea it's still got error
'( Login .WebForm1.DBConnection(string, string)'.

I just tried your vb.net code it's work! and then i was convert vb.net to c# code it's still
have got error as above. What's wrong?

regards,
Bee


BeeNarak
Newbie Poster
Offline

Re: Simple ASP.Net Login Page using C#


Jul 13th, 2005
Posts: 8
Reputation:

Join Date: Jul 2005

Solved Threads: 0

0 #7

I've got a full error when i change code "( Login .WebForm1.DBConnection(string,
string): not all code paths return a value".
Do you have any idea?

Thanks,
Bee


BeeNarak
Newbie Poster
Offline
Posts: 8
Reputation:

Join Date: Jul 2005

Solved Threads: 0
Re: Simple ASP.Net Login Page using C#
Jul 13th, 2005 0 #8

Hi Paladine,

As i've got an error '( Login .WebForm1.DBConnection(string, string)' now my code is


work. Yeah! i've put "return true;" on the c# code.

Cheers,
Bee

• Paladine
Master Poster
Offline

Re: Simple ASP.Net Login Page using C#


Posts: 793
Reputation:

Join Date: Feb 2003

Solved Threads: 26

Jul 13th, 2005 0 #9

yes, but it should be return True if login is Successful, and False if not

i.e. This return False should be un-commented out!!

C# Syntax (Toggle Plain Text) Help with Code Tags

1. if (objReader.GetValue(0) = 0)
2. {
3. lblMessage.Text = "Invalid Login !";
4. //return false;
5. }

Assistant Manager, Pharmacy Informatics


Wordpress Learning Blog
Updated : ASP.Net Login Code


Ads by Google

Security Task Manager


Detect and analyse background tasks and stealth Windows XP processes.
www.neuber.com/TaskManager


false420
Newbie Poster
Offline

Re: Simple ASP.Net Login Page using C#


Jul 19th, 2005
Posts: 5
Reputation:

Join Date: Jul 2005

Solved Threads: 0

0 #10

ive tried using this. ive used it once before with your vb.net and it worked pefectly. im
now learning c# and when i go to put this together the web.config keeps throwing this
error:

Parser Error Message: The data at the root level is invalid. Line 1, position 1.
Source Error:

Line 1: using System;


Line 2: <?xml version="1.0" encoding="utf-8" ?>
Line 3:

it points to the using system directive. anyone knw what would cause this?

1 2 > Last »

Quick Reply to Thread

• Message:


•• Post Reply
••
Transportation Design - AutoCAD Civil 3D Show Printable Version
Design Road Projects 75% Faster with Automatic
Documentation Updates!
Similar Threads
Virtualization Solutions
Optimize, Simplify, & Save Today. Learn About Updated : Simple ASP.Net Login
Page (ASP.NET)
Microsoft Solutions.
Simple ASP.Net Login Page (Using
Microsoft SQL Server® 2008 - Free Trial VB.Net) (ASP.NET)

Download the Free 180-day Trial of SQL Server®


2008 Enterprise Edition! Other Threads in the C# Forum

Windows Marketplace for Mobile


Previous Thread: C# online
Create Windows Mobile Applications And Turn
resources, help and advice?
Your Ideas Into Cash.
Next Thread: DataGridView with List
In Object to Display
Log Analysis Platform
Log analysis reports for application, network and
security log, download now!

.net access algorithm angle array barchart bitmap box broadcast c# capturing check checkbox client combobox control conversion convert csharp custom

database datagrid datagridview dataset datetime dbconnection degrees delegate design development disappear draganddrop drawing encryption enum event

excel file firefox form format forms function gdi+ httpwebrequest image index input install java label leak libraries list listbox mandelbrot math monodevelop

mouseclick msword mysql operator path pause photoshop picturebox pixelinversion post programming radians regex remote remoting richtextbox round server

sleep socket sql statistics stream string table tcpclientchannel text textbox thread time timer update usercontrol validation virtualization visualbasic visualstudio

webbrowser windows winforms wpf xml


ABOUT US | CONTACT US | ADVERTISE | DANIWEB | ACCEPTABLE USE POLICY |

©2003 - 2009 DaniWeb® LLC

Anda mungkin juga menyukai