Connection String Is Not Working Object Instance Reference Is Null
//'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
Solution 1:
There are many ways to connect to your SQL Server database within a C# app.
The First way, that is not recommended, is hard coding:
publicvoidCreateMySqlConnection() { MySqlConnectionStringBuildermyCSB=newMySqlConnectionStringBuilder(); 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; MySqlConnectionmyConnection=newMySqlConnection(myCSB.ConnectionString); }
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.ConfigurationrootWebConfig=
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
Post a Comment for "Connection String Is Not Working Object Instance Reference Is Null"