C# .NET - Error: Object reference not set to an instance of an object.

Asked By Elvin
28-Sep-11 03:54 PM
Error Message says: 
 

Server Error in '/' 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 23:         protected void Button1_Click(object sender, EventArgs e)
Line 24:         {
Line 25:             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
Line 26:             con.Open();
Line 27: 

Source File: C:\Users\D03072902\Desktop\zephyrAir2\zephyrAir2\Login.aspx.cs    Line: 25

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   zephyrAir2.Login.Button1_Click(Object sender, EventArgs e) in C:\Users\D03072902\Desktop\zephyrAir2\zephyrAir2\Login.aspx.cs:25
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565


Version Information: Microsoft .NET Framework Version:2.0.50727.5420; ASP.NET Version:2.0.50727.5420


-------------------------------------------------------------------------------------------------

Here is my code for Login.aspx.cs page ( Error Message location is highlighted in Yellow background):

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.SqlClient;

namespace zephyrAir2

{

public partial class Login : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);

con.Open();

string cmdStr = "select count(*) from UserAccounts where Username = '" + TextBox1.Text + "'";

SqlCommand Checkuser = new SqlCommand(cmdStr,con);

int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());

if (temp == 1)

{

string cmdStr2 = "select Password from UserAccounts where Password = '" + TextBox2.Text + "'";

SqlCommand pass = new SqlCommand(cmdStr2, con);

string password = pass.ExecuteScalar().ToString();

con.Close();

if (password == TextBox2.Text)

{

Session["New"] = TextBox1.Text;

Response.Redirect("ZephyrIndex.aspx");

}

else

{

Label1.Visible = true;

Label1.Text = "Invalid Password. Try Again Please.";

}

}

else

{

Label1.Visible = true;

Label1.Text = "Invalid Username. Try Again Please.";

}

}

}

}

----------------------------------------------------------------END OF CODE------------------------------------

How would I fix this issue and can you provide a fix to my code or give examples?

  Peter Bromberg replied to Elvin
28-Sep-11 08:23 PM
It looks like your ConnectionString setting in your web.config or app.config isn't specified correctly. Of course we cannot see that because you didn't provide it.
  Elvin replied to Elvin
28-Sep-11 08:58 PM
The web.config CODE IS:
<?xml version="1.0"?>
<configuration>
 
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
  
  
  
<connectionStrings>
   <!--        
   <add name="Zephyr_Air_DB2ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Zephyr_Air_DB2.accdb;
   Persist Security Info=True"   oviderName="System.Data.OleDb" />           
   -->
    <!--
<add name="ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\CyBeRfOrCe\Desktop\Zephyr_Air_DB2.accdb"
   providerName="System.Data.OleDb" /> 
    -->
    
  <add name="ConnectionString2" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\tblsZephyrAir.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
  <add name="useThisConnStringYOOOOO!" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\tblsZephyrAir.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>
  
  
  
<system.web>

<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
       
<authentication mode="Windows"/>

<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
 
    
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
    
    
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
    
</system.web>
  
  
  
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
  
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
  
  
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
  
</configuration>

  Elvin replied to Peter Bromberg
28-Sep-11 09:41 PM
I saw the error in that the fact that I used in code behind Login.aspx.cs page RegConnectionString instead of the two kinds of connection strings I got in the web.config file, so I used only the one that says useThisConnStringYOOOOO!  .

I had changed the piece of code as followed:

 protected void Button1_Click(object sender, EventArgs e)
        {
            // ***ERROR: Object reference not set to an instance of an object. 
            // Setting connection object
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["useThisConnStringYOOOOO!"].ConnectionString);
            // ***END 

            //Opening the connection
            con.Open();
.....

My web.config has the connection as :
 <add name="useThisConnStringYOOOOO!" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\C:\USERS\USERPCONE\DOCUMENTS\VISUAL STUDIO 2008\PROJECTS\ZEPHYRAIR2\ZEPHYRAIR2\APP_DATA\TBLSZEPHYRAIR.MDF;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />

---------------------------
I did the following and ran it but got another error saying:


Server Error in '/' Application.

The given path's format is not supported.

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.NotSupportedException: The given path's format is not supported.

Source Error:

Line 26:             // ***ERROR: Object reference not set to an instance of an object. 
Line 27:             // Setting connection object
Line 28:             SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["useThisConnStringYOOOOO!"].ConnectionString);
Line 29:             // ***END 
Line 30: 


WHAT DOES THAT MEAN>? AM I MISSING SOMETHING? Please assist with a sample code or a hint or something. I appreciate the response of at least knowing.
  Venkat K replied to Elvin
28-Sep-11 09:42 PM
Elvin,
You have specified the connection string in the web.config as "connectionstring2" and you have been reading the key in your code as "RegConnectionString".


Change the RegConnectionString to Connectionstring2 in your code or change the key value from connectionstring2 to RegConnectionString in your web.config file.

Thanks
  Elvin replied to Venkat K
28-Sep-11 09:52 PM
I had made the changes to what you said and therefore had a Professor tell me the same thing, but instead of changing to what you said I changed it to useThisConnStringYOOOOO! and had gotten the error I posted above to the Microsoft's MVP person above this post as reply.

But I followed your advice too and had changed it to what you said to change it in code behind page and had gotten the following error:

Server Error in '/' 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 43:                 SqlCommand pass = new SqlCommand(cmdStr2, con);
Line 44: 
Line 45:                 string password = pass.ExecuteScalar().ToString();
Line 46:                 con.Close();
Line 47: 

What I did is as follows:
// Setting connection object
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString);

I left the web.config file as followed(Only used the third one and the other ones are commented out:
<connectionStrings>
   <!--        
   <add name="Zephyr_Air_DB2ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Zephyr_Air_DB2.accdb;
   Persist Security Info=True"   oviderName="System.Data.OleDb" />           
   -->
    
    <!--
<add name="ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\CyBeRfOrCe\Desktop\Zephyr_Air_DB2.accdb"
   providerName="System.Data.OleDb" /> 
    -->
    
  <add name="ConnectionString2" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\tblsZephyrAir.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />  


    <!--  <add name="useThisConnStringYOOOOO!" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\C:\USERS\USERPCONE\DOCUMENTS\VISUAL STUDIO 2008\PROJECTS\ZEPHYRAIR2\ZEPHYRAIR2\APP_DATA\TBLSZEPHYRAIR.MDF;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />  -->
 </connectionStrings>
  
Note: I did as you said but got the error I posted above.

WHAT DOES THAT MEAN>? AM I MISSING SOMETHING? Please assist with a sample code or a hint or something. I appreciate the response of at least knowing.
  Elvin replied to Venkat K
28-Sep-11 10:07 PM
I also did the changes to the following Login.aspx.cs page:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace zephyrAir2
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
             
            // Setting connection object
           // SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["useThisConnStringYOOOOO!"].ConnectionString);
           SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString);

            //Opening the connection
            con.Open();

            string cmdStr = "select count(*) from UserAccounts where Username = '" + TextBox1.Text + "'";

            SqlCommand Checkuser = new SqlCommand(cmdStr,con);

            int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());
  
            if (temp == 1)
            {
                string cmdStr2 = "select Password from UserAccounts where Password = '" + TextBox2.Text + "'";
                SqlCommand pass = new SqlCommand(cmdStr2, con);

               // string password = pass.ExecuteScalar().ToString();
                string password = pass.ToString();
                con.Close();
                
                if (password == TextBox2.Text)
                {
                    Session["New"] = TextBox1.Text;
                    Response.Redirect("ZephyrIndex.aspx");
                }
                else
                {
                    Label1.Visible = true;
                    Label1.Text = "Invalid Password. Try Again Please.";
                }
            }
                else
                {
                     Label1.Visible = true;
                    Label1.Text = "Invalid Username. Try Again Please.";
                }

            }
        }
    }


Results:  I ran the page and set it as Start Up page and entered Username and Password but got just no error except that it actually did not redirect me to the ZephyrIndex.aspx page. But the minor issue is that the message from label in LogIn page says "Invalid Password . Try Again".
Can you help me?
  dipa ahuja replied to Elvin
29-Sep-11 02:16 AM
May be you are not addressing the correct table in which your username and passwords are saved.

There are three connectionString in your web.config and may be you may have three tables with same name.

Make sure you are addressing the correct DATABASE and correct TABLE in which your actual data are saved.
Create New Account
help
Correct Version of ASP.NET ?? .NET Framework My hosting service is using the following version of Microsoft .NET Framework and ASP.NET: Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210 Is this the correct Version? Ronc Expression Web Designer Discussions ASP
Where's the version information? .NET Framework I am having a problem with version information in one of my compact framework 2.0 VB.Net application which I am designing in Visual Studio 2005. After I compile the executable there is no version information available when viewing the file's properties in Windows. All my other projects have version information which is visible in Windows but I can't see any difference between these other
version information in office 2007 Office Hi all; As you know, when we want to look at version information in office 2003, we go to the Help menu and then execute the About Microsoft Office. . ., Now where can I find the version information in for example Office Word 2007? Thanks Office Miscellaneous Discussions Publisher 2007 (1) Word 2007 1) Office (1) PaulesMVP (1) Office button (upper left corner) - Options - - JoAnn Paules MVP Microsoft [Publisher] Tech Editor for "Microsoft Publisher 2007 For Dummies" Click Office icon. Click Word Options
driver pack "IEGD8". Can you point me in the right direction? I tried the newest version of the Intel driver 6.14.10.4926 (14.32.4) and this did not they're looking into it <sigh> . Regards, John / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / configuration file: Production - All languages.slx / / purpose: Microsoft Target Designer boot image build log / / created: 03 / 11 / 2008 06:05 PM / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / Emptying image run-time build at: 3 / 11 / 2008 6:06:13 PM. . . R: Building: "Base Component [Version 5.1.2600, R2010]". . . R: Building: "Base Performance Counters [Version 5.1.2600.2180, R2890]". . . R: Building: "Basic TCP / IP Networking [Version 5.1.2600.2180, R2890]". . . R: Building: "CDFS Version 5.1.2600.3333, R3333]". . . R: Building: "CD-ROM Drive [Version 5.1.2600, R620]". . . R: Building: "Certificate MMC Snap-In [Version 5.1.2600.2180, R2890]". . . R: Building: "Certificate Request Client & Certificate Autoenrollment [Version 5.1
thing. I've installed the hotfix rollup for Exchange 2007. Any idea? Exchange Admin Discussions INFORMATION (1) Server (1) Microsoft (1) Scanengineupdate (1) Forefrontdl (1) Service (1) Forefront (1) Package (1) Hi, Any error message in the Application log related to Exchange Transport Service? Hope this helps. Steve Antonio, CISSP Microsoft Exchange Support On Thu, 24 May 2007 09:21:16 -0700, "Zack" FSEIMC is responsible from the Forefront directory. This should provide more insight. Hope this helps. Steve Antonio, CISSP Microsoft Exchange Support On Thu, 24 May 2007 10:40:04 -0700, "Zack" Wed May 23 22:40:23 2007 ( 1764- 2100), "INFORMATION: Initializing virus scanning" Wed May 23 22:40:23 2007 ( 608- 1276 INFORMATION: Forefront Server Security Monitor is active." Wed May 23 22:40:23 2007 ( 3572- 3576), "INFORMATION: The Forefront Server Security service is starting." Wed May 23 22:40:26 2007 ( 3572- 3576), "INFORMATION: Initial Database Purge will begin in 3h 19m 33s (at 02:00)." Wed May 23