I'm pretty sure there's some quick and easy error in this code but somehow I've spent the last 2 hours with this and couldn't solve it.
App.config
:
<configuration>
<connectionStrings>
<add name="BO"
connectionString="Data Source=MyServer;Initial Catalog=BO;User ID=WebUser;Password=MyPasswd"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Class.cs
:
string connectionString = getNewConnection();
using (SqlConnection conn = new SqlConnection(connectionString)) { code }
Method.
public static string getNewConnection()
{
return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
}
Error:
Object reference not set to an instance of an object
on the line :
return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
EDIT:
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
You can simply access it using My. Settings. ConnectionString.
<connectionStrings> <add name="dbconnection" connectionString="Data Source=Soumalya;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System. Data. SqlClient" />
It should be:
ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
Edit:
You will need the corresponding libraries as well if you don't have them yet, as mentioned in the below answers I think its System.Configuration
So in full you should have:
public static string getNewConnection()
{
return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
}
Use these codes in the Class :
class Connection
{
public static string con
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With