0

I got this error Object reference not set to an instance of an object. I can't find what is the problem. Thanks

protected void Check_Clicked(Object sender, EventArgs e)
{

    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
                            ConnectionStrings["DbCar"].ConnectionString);
 .....
}

 <connectionStrings>
   <add name="ConnectionString" connectionString="Data  
    Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DbCar.mdf;Integrated 
    Security=True;User 
    Instance=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>
John Saunders
  • 160,644
  • 26
  • 247
  • 397
user3127986
  • 388
  • 1
  • 10
  • 33
  • 2
    Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jan 13 '14 at 15:14

4 Answers4

2

Your connection string name ConnectionString not DbCar

new SqlConnection(System.Configuration.ConfigurationManager.
                        ConnectionStrings["ConnectionString"].ConnectionString);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

The name of the connectionstring is ConnectionString rather than DbCar

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
                        ConnectionStrings["ConnectionString"].ConnectionString);
Shai
  • 25,159
  • 9
  • 44
  • 67
1

ConnectionStrings["DbCar"]

You do not have a connection string by that name. You need to rename your connection string from ConnectionString to DbCar or change the name in the code to ConnectionString.

Neil Kistner
  • 11,623
  • 2
  • 18
  • 17
0

Problem : You are refering to invalid connectionstring name. there is no ConnectionString in your configuration file with name DbCar.

Solution : you need to refer to the valid ConnectionString Name from the configuration file.

Solution 1: either change the name of DbCar to ConnectionString from the code.

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

Solution 2: or change the name of the connectionstring in config file from ConnectionString to DbCar.

<connectionStrings>
   <add name="DbCar" connectionString="Data  
    Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DbCar.mdf;Integrated 
    Security=True;User 
    Instance=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67