How to Get Connection String from App.config in .Net Application

Hello guys,

As we know that while interacting our SQL database to our or application we need to access the connectionstring of the SQL database. Once we access the connectionstring then we can use this to execute the SQL commands in our coding page. Now the question is when we have multiple forms in our desktop application we need to write the connectionstring on each window form to access the SQL database. So guys what to do to ignore this multiple writing of connectionstring on each form?  To avoid this we use an app.config file into our desktop application as we use the web.config file in web application. As we describe our connectionstring once in this app.config file we can access this connectionstring multiple times on multiple forms from app.config file. in this article we will tell you the process to access this.

Step 1: First you need to define your ConnectionString in app.config file by using the following code:

<?xml version="1.0"?>
    <add name="SchoolManagement" 
    connectionString="Data Source=.;Initial Catalog=SchoolManagement;Integrated Security=True"/>

Step 2: Now you must import the following namespaces in your form coding page

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

Step 3: After defining the Connectionstring in the app.config file you need to use the following code to access the connectionstring:

var connectionString=ConfigurationManager.ConnectionStrings["SchoolManagement"].ConnectionString;
admin (157 Posts)

Leave a reply

Your email address will not be published.

Comment moderation is enabled. Your comment may take some time to appear.