0

I have the following code

private string conn(string name)
    {
        return ConfigurationManager.ConnectionStrings[String.Format("{0}ConnectionString", name)].ConnectionString;
    }

But I keep getting the error below on the return statement.

System.NullReferenceException: Object reference not set to an instance of an object

Can you please tell me what is wrong with this?

1
  • Please make sure you setup connectionstring in web.config file. Commented Nov 27, 2012 at 20:35

3 Answers 3

1

Your code looks for connection string named name + "ConnectionString". It look's your web.config does not have connection string with this name. Add connection string with generated name or change the code like this:

    private string conn(string name)
    {
        var coll = ConfigurationManager.ConnectionStrings[String.Format("{0}ConnectionString", name)];
        if (coll != null)
        {
            return coll.ConnectionString;
        }
        else
        {
            return null;
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

This error arises if connectionstring return null, means you not setup connectionstring which normally setup in web.config file under

<connectionStrings>
    <add name="connectionString" connectionString="Server=  (local);Database=sampledb;Trusted_Connection=true;" providerName="System.Data.SqlClient"/> 
</connectionStrings>

Comments

0

What happens if the name passed in parameter to your method is null ??

You should look at this post, and other answers already provided on SO.

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.