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?
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
}
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