PurpleSmurph PurpleSmurph - 1 year ago 112
C# Question

Null Error Reading Connection String

I am getting a null reference exception when trying to connect to the database via


This is in a using statement and is the same code I've used in many other projects, but it keeps telling me null reference and I don't know why.

The connection string named is named correctly in the web.config which is in the same project so I wouldn't expect there to be permissions issues.

What have I missed?

I have seen the suggested answers, these are solved by putting the string in the Web.Config which is where the connection string is.

ConnectionString in Web.config

<add name="MyDB" connectionString="Data Source=192....; Initial Catalog=ProjectDb; Integrated Security=false; User Id=user; Password=password;" providerName="System.Data.SqlClient" />

Function to access DB

public static Company RetrieveCompany(int id)
var cmp = new Company();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
using (var cmd = new SqlCommand("RetreiveEmailProc", con))
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@companyId", id);

SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{ // code omitted }

catch(Exception ex)


return cmp;

Answer Source

I think it is related to you using ConfigurationManager instead of the WebConfigurationManager. It is possible your code resides in another folder with a different web.config and the ConfigurationManager can't handle that inheritance problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download