NullReferenceException trying to read connection string

c#, configurationmanager, nullreferenceexception, sql

Solution

You need to have entry in app.config for connection string in your window application.

If you don't have `App.Config` file then add it.

and put entry like below

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="GPSystemConnectionString"  connectionString="..." />
  </connectionStrings>
</configuration> 

In you .cs file

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

var connectionString=ConfigurationManager.ConnectionStrings["GPSystemConnectionString"].ConnectionString;

Problem

I have two projects. One is web & the other is windows forms. Web project connects to database but the windows project throws an exception NullReferenceException reading the connection string. I am using the same classes to connect both projects. Connection is established using LINQTOSQL. Here is my Connection string: ``` <connectionStrings> <add name="GPSystemConnectionString" connectionString="Data Source=.;Initial Catalog=GPSystem;User ID=***;Password=***" providerName="System.Data.SqlClient" /> </connectionStrings> ``` This is how i am reading it. ``` string CS = ConfigurationManager.ConnectionStrings["GPSystemConnectionString"].ConnectionString; ``` (Exception occurs on this line)..... (Object reference not set to an instance of an object.) Note: i am using same class to connect both projects.... one connects but the other fails. Please any one help me with this! Thank you in advance.

Original source