Reputation: 2107
I am getting a null reference exception when trying to connect to the database via ConnectionCtrings["MyDB"].connectionstring
.
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?
Edit: I have seen the suggested answers, these are solved by putting the string in the Web.Config which is where the connection string is.
Code: ConnectionString in Web.config
<connectionStrings>
<add name="MyDB" connectionString="Data Source=192....; Initial Catalog=ProjectDb; Integrated Security=false; User Id=user; Password=password;" providerName="System.Data.SqlClient" />
</connectionStrings>
Function to access DB
public static Company RetrieveCompany(int id)
{
var cmp = new Company();
try
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
con.Open();
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;
}
Upvotes: 1
Views: 604
Reputation: 156928
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.
Upvotes: 1