0

I have a problem connecting my database (created in SQL Server 2008 R2 Express) with c# in vs 2013

Here is the code I wrote

string connStr = ConfigurationManager.ConnectionStrings["newSchool"].ToString();
SqlConnection conn = new SqlConnection(connStr);

the error is NullReferenceException

5
  • 2
    What is the problem. Do you get an error message? Where is the conn.Open statement? Jan 6, 2014 at 14:45
  • What's the error? What problem are you having?
    – Matt
    Jan 6, 2014 at 14:45
  • And why is everybody using ConfigurationManager when you can easily access settings using Properties.Settings.Default? (Yes, I'd really like to know). Jan 6, 2014 at 14:46
  • NullReferenceException error at the first line Jan 6, 2014 at 14:48
  • I'd suggest including the ConnectionStrings section of your config file
    – Liath
    Jan 6, 2014 at 14:51

3 Answers 3

1

Change this:

string connStr = ConfigurationManager.ConnectionStrings["newSchool"].ToString();

to...

string connStr = ConfigurationManager.ConnectionStrings["newSchool"].ConnectionString;

Cheers -

0

Where did you define your connection string? In the app.config? Please send us the place where you configure this.

See http://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx for help.

See http://www.connectionstrings.com/ how to configure a connection string for .net

0

I assume that there is no connection string named newSchool. It is probably NewSchool or some other casing.


In response to your comment: You need to provide a proper connection string. The ConfigurationManager is used to get a value from the configuration. The NullReferenceException shows you that the setting you request is not there.

You need to create a connection string first using the settings manager and then you can access it.

2
  • newSchool is the name of the database Jan 6, 2014 at 14:49
  • 2
    Well, then you didn't grasp the concept of connection strings. Use the settings manager to create an actual connection string. Jan 6, 2014 at 14:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.