Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add connection string in Config File in WPF Application

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);
                }
            } 

enter image description here

Edit:

enter image description here

like image 963
Unbreakable Avatar asked Mar 21 '18 15:03

Unbreakable


People also ask

Where does WPF store connection string?

WinForms & WPF Applications The connection string should be added to your application's App. config file (Web. config if you are using ASP.NET).

Where should you store the connection string information?

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.


1 Answers

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.

like image 110
mm8 Avatar answered Oct 05 '22 23:10

mm8