0

I am trying to connect to my local database to select a sql database and print the column names but I keep getting this exception:

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

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.

Can somebody help me?

    string constr = 
  ConfigurationManager.ConnectionStrings[@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\NORTHWND.MDF;Integrated Security=True;"].ConnectionString;

    SqlConnection con = new SqlConnection(constr);
Cam Bruce
  • 5,632
  • 19
  • 34
  • 2
    You already have your connection string in the form of `constr`. The configuration manager's connection string is meant for retrieving a ConnectionString setting from a config file by name. You're currently using the entirety of a connection string as the name for lookup. – Jonathon Chase Jan 08 '19 at 22:08
  • The variable `constr` is your connection string. You are using it as an index into the dictionary of connection strings that the `ConfigurationManager` maintains: `ConfigurationManager.ConnectionStrings[constr]`. Either use the connection string alone, or use the name of the string that you have in the config file – Flydog57 Jan 08 '19 at 22:08
  • Ok I tried fixing it a little and it still has the same result – Anthony Karounis Jan 08 '19 at 22:51

2 Answers2

0

You're initializing the SqlConnection a little goofy. Try this:

SqlConnection con = new SqlConnection(constr);
Viggo Lundén
  • 748
  • 1
  • 6
  • 31
  • I have to use ConfigurationManager.ConnectionString because it's needed later on in the code. So you can understand better I'm trying to replicate the code from the GetData() method here: https://www.aspsnippets.com/Articles/Display-data-from-database-in-HTML-table-in-ASPNet.aspx – Anthony Karounis Jan 08 '19 at 22:32
  • It's hard to see what the problem is without seeing the rest of the code but try using: `ConfigurationManager.ConnectionStrings["constr"]` instead of `ConfigurationManager.ConnectionStrings[constr]` – Viggo Lundén Jan 08 '19 at 22:40
  • Ok I edited the code a little and it still has the same result – Anthony Karounis Jan 08 '19 at 22:54
0

If you need to use ConfigurationManager.ConnectionStrings then your connection string needs to be in your web.config in the configuration/connectionStrings section similar to this:

<configuration>
   <connectionStrings>
            <add name="db" connectionString="Data 
          Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL 
          Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\NORTHWND.MDF;Integrated Security=True;"/>
   </connectionStrings>
<configuration/>

You then access it by the value of the name attribute, like this:

var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
Cam Bruce
  • 5,632
  • 19
  • 34