0

Is my machine playing me today?

When I run the TestConnectionString() method of this object I get the error at the connection string setting.

public class CustomerDAL
{
   string connectionString = ConfigurationManager.ConnectionStrings["myConnection"].Name;

    public CustomerDAL()
    {

    }

    public string TestConnection()
    {
        System.Data.SqlClient.SqlConnection conn =  new System.Data.SqlClient.SqlConnection(connectionString);
        conn.Open();

        if (conn.State == System.Data.ConnectionState.Open)
        {
            return "Open";
        }
        else
        {
            return "Close";
        }
     }
}

2 Answers 2

7

If ConnectionStrings["myConnection"] returns null, then dereferencing it to get the Name property will fail in the constructor. Is that definitely not where the bug is?

Why not put a breakpoint on that line and take a look in ConfigurationManager.ConnectionStrings to check what it thinks it's got - and check very carefully for typos.

After that, put a breakpoint on the first line of the method, and check what the value of connectionString is. Passing in null to the SqlConnection constructor doesn't actually throw an exception, but you'd get an InvalidOperationException when you try to open it.

Sign up to request clarification or add additional context in comments.

1 Comment

Jon ~ I should've known better. I've got my StackOverFlowed. It was under "appSettings" section.
1

I have three suggestions

  1. you need to add a .dll reference for configuration manager
  2. recheck if your connection string is right
  3. check if you have more than one configuration file ex. web.config and app.config; so the ConfigurationManager is referencing the wrong file in the solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.