How to store Database Connection string in web.config and get Connection sting in .cs file ?
You need to add connection string under AppSettings or Connection strings tag
Example 1 : In appSettings section in web.config
Web.Config
<appSettings>
<add key="SQLConnection1" value="Database=MDS,Server=TestServer,UserID=sa,Password=sa" />
</appSettings>
In .cs file , Configuration Manager class is used to fetch connection string . See below code to see how :
string strSQLConnection1 = ConfigurationManager.AppSettings["SQLConnection1"];
But the better way is to add connection string in connectionstrings tag in web.config
See Web.Config for details :
<connectionStrings>
<add name="SQLConnection2" connectionString="Database=MDS,Server=TestServer,UserID=sa,Password=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>
You can retrieve the connection string in web.config using Configuration Manager class in .cs file :
Used this in my website. It worked fine
ReplyDelete