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



1. Create a Login Webform (HTML/ASP.NET)
- Include any control validation you feel necessary.

NorthCSharp.aspx

<%@ Page language="c#" Codebehind="Login.aspx.cs" AutoEventWireup="false" Inherits="NorthCSharp.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
    <head>
        <title>WebForm1</title>
        <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
        <meta name="CODE_LANGUAGE" content="C#">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
        <!-- <summary>
            |||||    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

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

]
<?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!

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;

private bool DBConnection(string strUserName, string strPassword)
		{
			OleDbConnection MyConn = new OleDbConnection(ConfigurationSettings.AppSettings["strConn"]);
			OleDbCommand MyCmd = new OleDbCommand("sp_ValidateUser", MyConn);

			MyCmd.CommandType = CommandType.StoredProcedure;

			OleDbParameter objParam1, objParam2;

			objParam1 = MyCmd.Parameters.Add("@UserName", OleDbType.Char);
			objParam2 = MyCmd.Parameters.Add("@Password", OleDbType.Char);
			//returnParam = MyCmd.Parameters.Add ("@Num_of_User", OleDbType.Integer);
            
			objParam1.Direction = ParameterDirection.Input;
			objParam2.Direction = ParameterDirection.Input;
			//returnParam.Direction = ParameterDirection.ReturnValue;

			objParam1.Value = txtUserName.Text;
			objParam2.Value = txtPassword.Text;

			try
			{
				if(MyConn.State == ConnectionState.Closed)
				{
					MyConn.Open();
					
				}

				OleDbDataReader objReader;
				objReader = MyCmd.ExecuteReader(CommandBehavior.CloseConnection);

				while(objReader.Read())
				{
				
					if ((string)objReader.GetValue(0) != "1")
					{
						lblMessage.Text = "Invalid Login!";
						//return false;
					}
					else
					{
						objReader.Close();
						return true;
					}
					
				}		
			
			}
			catch(Exception ex)
			{
				lblMessage2.Text = "Error Connecting to the database!";
				//return false;
			}
				
		
		}

Could you please advise if you have any idea?
Thank you very much,

BeeNarak

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:

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

Should be

objReader.GetValue(0) = 0

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

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;

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;
using System.Web.Security;
using System.Data.OleDb;
using System.Configuration;

namespace Login
{
	/// <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 lblMessage2;
		protected System.Web.UI.WebControls.Label lblMessage;
		//protected System.Web.UI.Page.Session;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
		}

		private bool DBConnection(string strUserName, string strPassword)
		{
			string LoginSQL;
			OleDbConnection MyConn = new OleDbConnection(ConfigurationSettings.AppSettings["strConn"]);
			OleDbCommand MyCmd = new OleDbCommand("sp_ValidateUser", MyConn);

			MyCmd.CommandType = CommandType.StoredProcedure;

			OleDbParameter objParam1, objParam2;

			objParam1 = MyCmd.Parameters.Add("@UserName", OleDbType.Char);
			objParam2 = MyCmd.Parameters.Add("@Password", OleDbType.Char);
			//returnParam = MyCmd.Parameters.Add ("@Num_of_User", OleDbType.Integer);
            
			objParam1.Direction = ParameterDirection.Input;
			objParam2.Direction = ParameterDirection.Input;
			//returnParam.Direction = ParameterDirection.ReturnValue;

			objParam1.Value = txtUserName.Text;
			objParam2.Value = txtPassword.Text;

			try
			{
				if(MyConn.State == ConnectionState.Closed)
				{
					MyConn.Open();
					
				}

				OleDbDataReader objReader;
				objReader = MyCmd.ExecuteReader(CommandBehavior.CloseConnection);

				while(objReader.Read())
				{
				
					if (objReader.GetValue(0) = 0)
					{
						lblMessage.Text = "Invalid Login!";
						//return false;
					}
					else
					{
						objReader.Close();
						return true;
					}
					
				}		
			
			}
			catch(Exception ex)
			{
				lblMessage2.Text = "Error Connecting to the database!";
				//return false;
			}
				
		
		}
	
		
		#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) //Meaning the Control Validation was successful!
			{	//Connect to Database for User Validation
				//int intMaxLoginAttempts = ((Int32)Session["Num_of_Tries"]);
				if(DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()))
				{
					//if(Session["Logged_IN"].Equals("Yes")) //Use to Validate on other pages in the application
					//{
						//Session["Logged_IN"].Equals("Yes");
						FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false); //default.aspx Page!
						//Response.Redirect("default.aspx");
						//Response.Redirect("../Login.aspx?ReturnUrl=/default.aspx");
					//}
					//lblMessage.Text = "Success Full";
					
				}
				else 
				{	//Credentials are Invalid
					lblMessage.Text = "Sorry! Your login or password is incorrect. \n\n Please log in again.";
					//Session["LoginCount"] = ((Int32)Session["LoginCount"]) + 1;
					//Response.Redirect ("default.aspx");
				}
				/*if(Session["LoginCount"].Equals(intMaxLoginAttempts))
				{
					Response.Redirect("Denied.aspx");
				}

				if(((Int32)Session["Num_of_Tries"]) > 2)
				{
					Response.Redirect("Denied.aspx");
				}*/
													 
			}
		}
	}
}

No worries...

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

(int)objReader.GetValue(0) = 0

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

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

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

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!!

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

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?

Are those lines in web.confg? Using system; should not be in the Web.Config file.

Remove that using system line

Provide some of the code giving you the issue.

Thanks

using System;
<?xml version="1.0" encoding="utf-8" ?>

<configuration>
<appSettings>
<add key="strConn" value="Data Source=(local);database=LoginTest;User id=#;Password=#;"/>
</appSettings>

<system.web>


i know it seemed wierd to me cuz usually you have to compile hings with using statements. im new so i wasnt sure. i had just copied yours up top and inserted my stuff

ive edited it to this:

<configuration>
<appSettings>
<add key="strConn" value="Data Source=(local);database=LoginTest;User id=#;Password=#;"/>
</appSettings>
</configuration>


and it works but for some reason i get this but there is no northwind stuff anywhere.

System.Data.SqlClient.SqlException: Invalid object name 'NorthWindUsers'. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at login.WebForm1.DBConnection(String txtUser, String txtPass)Error Connecting to the database

Ok, my bad. Sorry about that. See... even I goof on copy paste. Hehe. But that doesn't excuse you... :) :) :) See, you should understand what you are copying and pasting. :lol: :lol:

Saying that. You are sure your SQL Db has the NorthWindUsers Table created? Because the error message is saying that you don't.

now i see where im getting hung up at. i can understand the code pretty well but i cant figure out why my stored procedure is telling me that the @username and @password is invalid columns, i thought thats where it does the match from the entered data.
SELECT COUNT(*) AS Num_of_User
FROM tblUser
WHERE (((tblUser.U_Name)=[@UserName]) AND ((tblUser.U_Password)=[@Password]));

im just messing around with it to help me get better with .net

it will also tell me i must declare the username and password variables in the stored procedures, ive never really worked with strored procedures before

I've converted the code to OleDb but I keep getting this error message:

System.Data.OleDb.OleDbException: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. at System.Data.OleDb.OleDbCommand.ProcessResults(Int32 hr) at System.Data.OleDb.OleDbCommand.ApplyAccessor(Int32 count, DBBindings bindings) at System.Data.OleDb.OleDbCommand.CreateAccessor() at System.Data.OleDb.OleDbCommand.InitializeCommand(CommandBehavior behavior, Boolean throwifnotsupported) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at TrackMyFood.uLogin.DBConnection(String txtUser, String txtPass) in c:\inetpub\wwwroot\trackmyfood\ulogin.aspx.cs:line


And here is my code:

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;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;

namespace TrackMyFood
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	public class uLogin : 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)
		{
			OleDbConnection myConn = new OleDbConnection(ConfigurationSettings.AppSettings["Nutrition"]);
			OleDbCommand myCmd = new OleDbCommand("sp_ValidateUser", myConn);
			myCmd.CommandType = CommandType.StoredProcedure;
			
			OleDbParameter objParam1;
			OleDbParameter objParam2;
			OleDbParameter returnParam;

			objParam1 = myCmd.Parameters.Add ("@UserName", OleDbType.Char);
			objParam2 = myCmd.Parameters.Add ("@Password", OleDbType.Char);
			returnParam = myCmd.Parameters.Add ("@Num_of_User", OleDbType.Integer);

			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;
			}
		
		}
	}
}

Please help! Thanks. W

OK a don't see anything wrong with your code, what version of SQL server are you using? Microsoft Recommends that if you have version 7.0 or later (includes MSDE) the SqlClient should be used.

But also inorder to use OleDB you need to consider this: The .NET Framework Data Provider for OLE DB requires the installation of MDAC 2.6 or later.

Not sure if that helps much, but have you tried making any other connections to the SQL Server using OleDb? Also, have you tried removing the using System.Data.SqlClient and recompiling and see what happens? I know it sounds strange and too simplistic, but stranger things have happened that can make an application run.

Hope this helps.

P.S. When does this error occur? OnCompile? Provide as much details as you can on the sequence that generates this message.
:cool: :cool: :cool:

My apologies, I should have mentioned it earlier...

I'm using an Access Database and I'm running the StoredProcedure from your VB.Net example.

SELECT COUNT(*) AS Num_of_User
FROM tblUser
WHERE (((tblUser.U_Name)=[@UserName]) AND ((tblUser.U_Password)=[@Password]));

The Access table is as follows:
u_ID - Autonumber
u_Name - Text
u_Password - Text


The application builds and compiles. The error occurs when the cmdsubmit is called, which calls the DBConnection. Specifically, it errors on the ExecuteNonQuery.

myCmd.ExecuteNonQuery();

Thanks again for the help! W.

Hmm, I would check the security settings on your Access DB.

I can't see anything wrong with the code... hmm

I will look into it again tomorrow!

My apologies, I should have mentioned it earlier...

I'm using an Access Database and I'm running the StoredProcedure from your VB.Net example.

SELECT COUNT(*) AS Num_of_User
FROM tblUser
WHERE (((tblUser.U_Name)=[@UserName]) AND ((tblUser.U_Password)=[@Password]));

The Access table is as follows:
u_ID - Autonumber
u_Name - Text
u_Password - Text


The application builds and compiles. The error occurs when the cmdsubmit is called, which calls the DBConnection. Specifically, it errors on the ExecuteNonQuery.

myCmd.ExecuteNonQuery();

Thanks again for the help! W.

Paladine
can you attach the file and database it will be more helpful

HI
i used the sql database and i did your code my problem is all the input give me the message invalid passward although it is stored in the database.

the sql code work fine but give me invild message with any input eather wrong or right

Are you using Visual Studio or Web Matrix?

If you are using Visual Studio, have you stepped though the code?

Comment out the Invalid Login portion of the code and see what error message you are getting from ASP.Net

Yes i am using Visual Studio?
but can you attach your file it may help in my stiuation
thanks

Hi
THANKS FOR Paladine for nice code
did any one try the sql code it doesn't work with me
no error but the invalid message display all the time with any input?
if any one try the sql and it work can help me ????????????

thanks again for help

Anyone that would be so kind and post the stored procedure, I'm not able to get the northwind SP, and would therefore be happy if someone could show it, as i will try to get it up and running on a MS SQL 2000 server.

I'm trying with this so far:

CREATE PROCEDURE sp_ValidateUser
@UserName varchar(16), @Password varchar(16)
AS
SELECT COUNT(*) as Num_of_Users
FROM USERS
WHERE Users.username LIKE @UserName AND Users.password LIKE @Password

it returns 1 column as Num_of_Users with a either 1 or 0 depending on valid or invalid user/password


The login form ends up just saying "Invalid Login, please try again!"


Regards
Train

I did manage to create the SP myself. If anyone has the same problem this was what i wrote in my SP:

CREATE PROCEDURE sp_ValidateUser
@UserName varchar(16), @Password varchar(16)
AS
DECLARE @Num_of_User INT
SELECT @Num_of_User = COUNT(*) FROM USERS WHERE (Users.username LIKE @UserName) AND (Users.[password] LIKE @Password)
RETURN @Num_of_User

GO

Table's is abit diffrent compared to the exsampel, hope you can use it anyway

The start of the tutorial states where to find the basis on which this tutorial is built.

But here is the original Stored Procedure:

CREATE PROCEDURE sp_ValidateUser /* How it would appear in QUERY ANALYZER */
(
@UserName VARCHAR(50) = NULL,
@Password VARCHAR(50) = NULL,
@Num_of_User INT = 0
)
AS
SET @Num_of_User = (SELECT COUNT(*) AS Num_of_User
FROM NorthWindUsers
WHERE UserName = @UserName AND Password = @Password)
RETURN @Num_of_User

If you are still having troubles let me know...

Also one thing to note. I would avoid using LIKE as you will can have the chance of a guess working for the login, or even more likely to have multiple records.

A login should grab one, and only one record.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.