-3

//'Object reference not set to an instance of an object.' Please Do not mark it as redundant question . I have tried almost all the methods to make a connection string

first one is by :

string connectionString = ConfigurationManager.ConnectionStrings["ClinicalConnectionString"].ConnectionString;


the second one :

   string connectionstringgg = Properties.Settings.Default.ClinicalConnectionString;


third method is by :

 ConnectionStringSettings connectionSetting = ConfigurationManager.ConnectionStrings["ClinicalConnectionString"];

//the name of the connection i made

SqlConnection connection = new SqlConnection(connectionString);

In the app config:

<connectionStrings>
    <add name="ClinicalDAO.Properties.Settings.ClinicalConnectionString"
        connectionString="Data Source=DESKTOP-I07DSQC;Initial Catalog=db_clinics;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>

In the web config

  <connectionStrings>
    <add name="ClinicalDAO.Properties.Settings.ClinicalConnectionString"
        connectionString="Data Source=DESKTOP-I07DSQC;Initial Catalog=db_clinics;Integrated Security=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

ANY HELP PLEASE it still give me the same error : /////'Object reference not set to an instance of an object.'///

5
  • 5
    The name needs to match the name property in your config file, not just the last part, so e.g. "ClinicalDAO.Properties.Settings.ClinicalConnectionString" Commented Jul 29, 2018 at 14:10
  • 1
    You can most likely run the code in a debugger and check what the ConnectionStrings collection contains. But in any case what was said is true, the whole name must be used to access the string. Commented Jul 29, 2018 at 14:11
  • @sellotape you are totally right . Thank you. Commented Jul 29, 2018 at 14:22
  • 1
    Possible duplicate of What is a NullReferenceException, and how do I fix it? Commented Jul 29, 2018 at 14:33
  • You said "Please Do not mark it as redundant question" but I'm afraid there is nothing special here, just a regular NullReferenceException, which you need to learn to diagnose. In the first example you give, the value before .ConnectionString will return null because the name you asked it to look for in the config doesn't exist. Commented Jul 29, 2018 at 16:49

1 Answer 1

1

There are many ways to connect to your SQL Server database within a C# app.

  1. The First way, that is not recommended, is hard coding:

    public void CreateMySqlConnection()
    {
        MySqlConnectionStringBuilder myCSB = new MySqlConnectionStringBuilder();
        myCSB.Port = 3307;
        myCSB.Host = "localhost";
        myCSB.UserId = "root";
        myCSB.Password = "mypassword";
        myCSB.Direct = true;
        myCSB.Compress = true;
        myCSB.Database = "demobase";
        myCSB.MaxPoolSize = 150;
        myCSB.ConnectionTimeout = 30;
        MySqlConnection myConnection = new MySqlConnection(myCSB.ConnectionString);
    }
    

from: https://www.devart.com/dotconnect/connection-strings.html?gclid=CjwKCAjwy_XaBRAWEiwApfjKHt-Yn6Ja43anKj0cvAzDHL5eNDHKvaxwnq5IEsVyHY-rR3GECsa6shoCZH8QAvD_BwE

  1. The second way, anwsering the question being already anwsered by @sellotape at the author comments, is puting the connection string at you web.config:

    <add name="MovieDB"
         connectionString="Data Source=LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf"     
         providerName="System.Data.SqlClient"/>
    

to read it:

System.Configuration.Configuration rootWebConfig =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
        System.Configuration.ConnectionStringSettings connString;
        if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString =
                rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"];
            if (connString != null)
                Console.WriteLine("MovieDB connection string = \"{0}\"",
                    connString.ConnectionString);
            else
                Console.WriteLine("No MovieDB connection string");
        }

The name at your web.config tag 'name'

    <add name="MovieDB".....

has to be the same one from your c# code:

    connString = rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"]

You don´t need to specify a large name as you did: "ClinicalDAO.Properties.Settings.ClinicalConnectionString"

Make it smaller and simple.

from: https://msdn.microsoft.com/en-us/library/ms178411.aspx

Don´t forget to secure your connection string at your web.config. Please, read this: https://msdn.microsoft.com/en-us/library/ms178372.aspx

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

2 Comments

I already have the answer. But you have made a really well answer with references and mentioned the righteous way , the hardcoded and how to make it secure. Thank you.
The first way is also not recommended as it applies to MySql and the question is tagged SQL Server 😀

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.