I am a beginner and learning WPF Application. I have a simple project and in that I want to read DB Configuration string from App.Config File. But I am not able to do so. Below is my attempt:
APP.Config File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="DBCS" connectionString="Data Source=.\;Initial Catalog=Connect;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
CS Code:
public static void GetDataFromDB()
{
//var CS = @"Data Source=.\;Initial Catalog=Connect;Integrated Security=SSPI";
// ABOVE CODE WORKS FINE
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select * from tblTenant", con);
DataSet ds = new DataSet();
da.Fill(ds);
}
}
Edit:
WinForms & WPF Applications The connection string should be added to your application's App. config file (Web. config if you are using ASP.NET).
Connection strings in configuration files are typically stored inside the <connectionStrings> element in the app. config for a Windows application, or the web. config file for an ASP.NET application.
You need to put the connnection string in the App.config
of the running WPF application and not in the DAL or any other class library.
The ConfigurationManager
class reads the configuration file of the running executable.
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