Avatar of Adnan
AdnanFlag for Norway

asked on 

Having problom with Login1_Authenticate1, i am getting error message: Object reference not set to an instance of an object

hi

iam getting error when i try to logon, i am builting a login.aspx function for my web page, and iam having problom to complet it...can somone help me throw this?

here is the error message iam getting on Line 40::


Server Error in '/LaPaz' Application.
--------------------------------------------------------------------------------

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 38:
Line 39:
Line 40:         if (Membership.ValidateUser(userTB.Text.ToString(), passwordTB.Text.ToString()))
Line 41:         {
Line 42:             FormsAuthentication.RedirectFromLoginPage(userTB.ToString(), false);
 

protected void Login1_Authenticate1(object sender, AuthenticateEventArgs e)
    {
        TextBox userTB = (TextBox)Login1.FindControl("txtUserName");
        TextBox passwordTB = (TextBox)Login1.FindControl("txtPassword");
 
 
 
        if (Membership.ValidateUser(userTB.Text.ToString(), passwordTB.Text.ToString()))
        {
            FormsAuthentication.RedirectFromLoginPage(userTB.ToString(), false);
        }
        else
        {
            //LegendStatus.Text = "Invalid user name or password!";
 
        }
    }

Open in new window

Programming Languages-Other.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
abel
Avatar of abel
abel
Flag of Netherlands image

The most likely source is that your FindControl did not find the control. In which case Nothing is returned, in which case the error you mentioned is returned.
Avatar of abel
abel
Flag of Netherlands image

to resolve: check (with cut / paste) whether the names txtPassword and txtUserName are really there. In addition, you may add something like the following to find out in code whether the textboxes are found:

    TextBox userTB = (TextBox)Login1.FindControl("txtUserName");
    TextBox passwordTB = (TextBox)Login1.FindControl("txtPassword");
 
    If userTB Is Nothing OrElse passwordTB Is Nothing Then
        Throw New ControlNotFoundException()  'TBD
    End If

Open in new window

Avatar of abel
abel
Flag of Netherlands image

Oops, sorry, mixing VB and C#. Syntax as follows (and please replace Nothing in my first post with null).

    TextBox userTB = (TextBox)Login1.FindControl("txtUserName");
    TextBox passwordTB = (TextBox)Login1.FindControl("txtPassword");
 
    if userTB == null || passwordTB == null
        Throw New ControlNotFoundException();  //TBD

Open in new window

Avatar of abel
abel
Flag of Netherlands image

too early in the morning, sorry for the clutter... missing accoladed in the if statement... :S
Avatar of Adnan
Adnan
Flag of Norway image

ASKER

i have try your code...but now i have messed up alot with the code, iam getting this error message know saying: Error      1      'login' does not contain a definition for 'cmdSubmit'      H:\My Documents\LaPaz\login.aspx.cs      45      14      H:\My Documents\LaPaz\

it can not find id= "cmdSubmit" from the code......but it is there..?!

Can somone check were i have done something wrong?

here is code for my login.aspx page: 
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
 
    <asp:Login ID="Login1" runat="server">
        <LayoutTemplate>
                 <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><asp:button id="cmdSubmit" runat="server" text="Submit" borderstyle="Solid" OnClick="cmdSubmit_Click"></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>
        </LayoutTemplate>
    </asp:Login>
 
 
</asp:Content>
 
******************Here is the code behind login.aspx.cs file*********
 
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
 
public partial class login : System.Web.UI.Page
{
 
 
    public void Page_Load(object sender, EventArgs e)
    {
 
        if (!this.IsPostBack)
            ViewState["LoginErrors"] = 0;
 
    }
 
  
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }
    public void InitializeComponent()
    {
        
  //Error here, "login does not contain a defination for cmdSubmit"      this.cmdSubmit.Click += new System.EventHandler(this.cmdSubmit_Click);
        this.Load += new System.EventHandler(this.Page_Load);
 
    }
    //protected void Login1_Authenticate1(object sender, AuthenticateEventArgs e)
    public void cmdSubmit_Click(object sender, System.EventArgs e)
    {
        TextBox userTB = (TextBox)Login1.FindControl("txtUserName");
        TextBox passwordTB = (TextBox)Login1.FindControl("txtPassword");
 
        if (Page.IsValid)
        {
            if (DBConnection(userTB.Text.Trim(), passwordTB.Text.Trim()))
            {
                FormsAuthentication.RedirectFromLoginPage(userTB.Text, false);
            }
            else
            {
                //lblMessage.Text = "Invalid Login, please try again!";
            }
        }
 
        //TextBox userTB = (TextBox)Login1.FindControl("txtUserName");
        //TextBox passwordTB = (TextBox)Login1.FindControl("txtPassword");
 
 
 
        //if (Membership.ValidateUser(userTB.Text.Trim(), passwordTB.Text.Trim()))
        //{
        //    FormsAuthentication.RedirectFromLoginPage(userTB.Text.Trim(), false);
        //}
        //else
        //{
        //    //LegendStatus.Text = "Invalid user name or password!";
 
        //}
    }
   public bool DBConnection(string txtUser, string txtPass)
    {
        SqlConnection myConn = new SqlConnection(ConfigurationSettings.AppSettings["MyMembershipConnString"]);
        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;
        }
 
    }
   
}

Open in new window

Avatar of abel
abel
Flag of Netherlands image

No, cmdSubmit is not directly available. It is inside the template LayoutTemplate, which means it is "hidden" for the type system.

What one would normally do in such case is use the OnCommand (or similar) property of asp:button from the ASP code window. If you do want to set that handler programmatically, you have to find the control by using FindControl the same way you do for the txtUserName and txtPassword controls, i.e.:

Button cmdSubmit = (Button) Login1.FindControl("cmdSubmit");

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of abel
abel
Flag of Netherlands image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of abel
abel
Flag of Netherlands image

a B? Guess you needed some more info? Could've just asked... But thx for the points anyway ;)
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo