Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException trying to read connection string

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.

like image 936
Neo Avatar asked Dec 04 '22 07:12

Neo


2 Answers

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;
like image 179
शेखर Avatar answered Feb 16 '23 15:02

शेखर


I always struggle with this issue of null reference with the ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString when I have the data access layer in a different project/library than the executable. I often use the following to help debug the location of the configuration file at runtime:

var configfile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var path = configfile.FilePath;
like image 43
fradsham Avatar answered Feb 16 '23 15:02

fradsham