Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a connection string using an app.config file in C# [duplicate]

Currently i manually define my connection string in my C# code:

string ConnectionString = "Data Source=C;Initial Catalog=tickets;Integrated Security=True";
SqlConnection Conn = new SqlConnection(ConnectionString);
Conn.Open();

In my project i have an app.config file and i can see that it has a connection string. It looks like this:

<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
    <add name="ticketNotification.Properties.Settings.ticketsConnectionString"
        connectionString="Data Source=C;Initial Catalog=tickets;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

How can i define the connection string based on the app.config file in the same folder as my application?

like image 522
PriceCheaperton Avatar asked Nov 29 '22 11:11

PriceCheaperton


1 Answers

Modify your application with this

App.config file

<?xml version="1.0"?>
  <configuration>
    <configSections>
    </configSections>
    <connectionStrings>
         <add name="ticketNotification.Properties.Settings.ticketsConnectionString"
              connectionString="Data Source=C;Initial Catalog=tickets;Integrated Security=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
  </configuration>

and here is your code behind file. You need to use System.Configuration Namespace. System.Configuration namespace contains ConfigurationManager class which is used to get connection string from app.config/web.config files.

As this is a windows application you have App.config file where you have defined your connection string. To get that connectionstring defined in the configuration file you need to use below line of codes inside your required eventhandler

Add this namespace to your code behind (ex: Form1.cs) file

using System.Configuration;

And here inside the eventhandler add/modify these codes

  string myConnectionString = ConfigurationManager.ConnectionStrings["ticketNotification.Properties.Settings.ticketsConnectionString"].ConnectionString;

  using(SqlConnection Conn = new SqlConnection(myConnectionString))
  {
     Conn.Open();
     //Define the SQL query need to be executed as a string

    //Create your command object

    //Create Dataset,Dataadapter if required

    //add parameters to your command object - if required

   //Execute your command

   //Display success message
 }
like image 51
Chandan Kumar Avatar answered Dec 06 '22 05:12

Chandan Kumar