How to get connection strings to various databases in ASP.NET 2.0

How to use connection strings to various Databases in ASP.NET 2.0

Some of the values and strings are used across all the pages of a website. It is a tedious process to code those values and strings in each page of the website.

The connection string will be used in many pages of the web site if you are developing a database driven website. Let us say that you have hard coded the connection string in all the pages, around 30 pages. Now if the value of the connection string changes, you have a headache of changing all the values of the connection string in all the 30 pages. This can’t be done easily and if you are to change the string again after about one month, it is going to be a tedious task.

Hence in such scenarios it is a practice to store those values in a central repository from where you can retrieve it and use it in all the pages. For example if you store the connection string in a central place like a web.config file you can retrieve those connection strings from the web.config file and use it. Previous to ASP.Net 2.0 the connection strings were stored in web.config file as given below:

<add key=”connectionString” value=”connection_string_value_here” />



The connection string is stored as key and value pair in the <appSettings> element of the web.config file. This value can be retrieved by writing code like:


Instead of using the <appSettings> section you can also add your own sections in the web.config file to have all your string value that you will be using in your application.

ASP.Net 2.0 provides with a special class for retrieving those customized string values.

This class is called the ConfigurationManager class.

Using this class you will be retrieving values by writing the following code for the above config file.


To open the ConnectionStrings section of the web.config file, you can use code like


The above code is used to retrieve ConnectionStrings from the web.config file as given below:

<add name=”connectionString” connectionString=”Data Source=.;Initial Catalog=db_products;Integrated Security=True” providerName=”System.Data.SqlClient” />

This code comes under the <configuration> section of the web.config file.

Here you can use the connectionStrings tag to store multiple Connection string to multiple databases and use it at your might.


<add name=”connectionString” connectionString=”Connect_String_Value” providerName=”Connection_Provider” />

<add name=”myCString” connectionString=”Connect_String_Value” providerName=”Connection_Provider” />

<add name=”newCString” connectionString=”Connect_String_Value” providerName=”Connection_Provider” />

You can use it in you code like :

1. ConfigurationManager.ConnectionStrings[“connectionString”].ConnectionString

2. ConfigurationManager.ConnectionStrings[“myCString”].ConnectionString

3. ConfigurationManager.ConnectionStrings[“newCString”].ConnectionString

Happy Connecting to database 🙂

Create a Simple Application to Search a User Name from Database in AJAX


Many of us does not know how to use AJAX and roaming in the Internet for one sample application from which we can start building our knowledge in AJAX (Asynchronous JavaScript and XML).


I have a small web application whose backend database is in MySQL and the Server side scripting language is PHP (Hypertext Pre Processor).


First we should why we need AJAX in our application. We were pretty happy with our own standard applications where we use POST or GET method to go to database and Fetch data and display it in the Page.


In the earlier cases if we want a small database access then also we need to POST the form with variables and then execute the Database query and then fetch and Display data back in the Browser.


Suppose we want to validate a user name, i.e we want to check if the user name already exists or not before inserting the user details in the database.


In this case we need 2 server accesses.


  1. First time send data to server to check the user name from database.
  2. GET Data back to the Client with the details such as the name already exists or Name does not exist.
  3. Again send the full form in the server with the complete user details to insert the user in the database.


So, if our form is pretty long and contains images and JavaScripts other stuffs then these elements will load again along with the form. This will hamper the performance of the site.


So we can use AJAX here to minimize the load time and Access time.


As we know AJAX is not a new coding language. It is a Methodology. This methodology uses XMLHTTP Request to send data to server and get back the results with JavaScript.


Now we will create a JavaScript document named ServerReq.js, which will contain all the utility functions that we can use through out the application.



* File: ServerReq.js

*This file creates the instance of xmlHttpRequest object, sends and

* Receives the request and response respectively.



* Static script to instantiate XMLHttp object for different browsers.


var clientHttpHandler;

clientHttpHandler = create();



* This method creates the xmlHttpRequest object and returns it.


function create()         


            var xmlHttpRequest = false;


            //Internet Explorer



                        xmlHttpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);


            catch (xml2Exception)




                                    xmlHttpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);


                        catch (xmlException)


                                    xmlHttpRequest = false;




            //Netscape, Mozila, Firefox, Safari, Opera

            if (!xmlHttpRequest && typeof XMLHTTPRequest == ‘undefined’)




                                    xmlHttpRequest = new XMLHttpRequest();


                        catch (genException)


                                    XMLHttpRequest = false;



            return xmlHttpRequest;



* This method sends the request to the server url according to the

* Passing parameters. It sets the user’s response function to the

* onreadystatechange event of the xmlHttpRequest object.


function send(httpMethod, serverUrl, isAsync, respFunc)


  , serverUrl, isAsync);

            clientHttpHandler.onreadystatechange = respFunc;




* This method checks the state and the status of the response and

* Depending on that fetches the response text.

* readystate: 0 – uninitialized, 1 – loading, 2 – loaded, 3 – interactive, 4 – complete


function receive()


            //var response = “”;



                        if (clientHttpHandler.readyState == 4) // Completed


                                    if (clientHttpHandler.status == 200) // “OK”


                                                return true;


                                    else if (clientHttpHandler.status == 403) // “Forbidden”


                                                alert(“Error: Access denied. Please check the permissions!”);


                                    else if (clientHttpHandler.status == 404) // “URL Not Found”


                                                alert(“Error: URL not found. Please check the URL!”);


                                    else // Miscellaneous


                                                alert(“Error: status code ” + clientHttpHandler.status);



                        return false;


            catch (genException)






In this function we have created an XMLHttpRequest object depending on the type of browser.

Then we have used the OnReadyStateChange event of the Object that will check if the Request has been completed or not.


This event has 4 ready states:





The request is not initialized


The request has been set up


The request has been sent


The request is in process


The request is complete



So each time the ready state changes the function receive() will be executed.

But we will look for the ready state 4 as in this state the request is marked as completed. SO whatever request we have sent that is being completed and we can now access the response data now.


Now we will create a Function that will use the above script to send, parse and display data to the webpage from where we have requested it.



* File: SendAjaxRequest.js

This function we will call from our webpage with the values that

Needs to be sent to the server for processing.



function SendReqSearchRequest(userName){


          We will append a random number each time we need to

          Send the request. So that browsers does not cache the request

          And every time a fresh page will be executed.


        var rand = Math.floor(Math.random()*1000001);


        // The URL where our background page resides


         sURL = “../utility/searchuser.php”; // I have used a relative path



         I have here used the GET method to send data to the background

         Page so builds the query string here.


         queryString = “?rand=” + rand + “&username=” + userName;


         // Append the query string at the end of the URL


            sURL += “?” + queryString;


            //Attach a function which will take care of the data when it comes back


         clientFunc = populateSearchResultData;


         // If this request is a synchronous or not.

         // If we use multiple synchronous requests at a time then only the

        // Last request will be executed.


            isSync = true;


        // Now send the request.


            send(“GET”, sURL, isSync, clientFunc);





* This method populates the returrn data


function populateSearchResultData ()


            var opStr = “”;


            if (receive())


                         response = clientHttpHandler.responseText;


                         if(response == “NF”){

                                    document.getElementById(“ResultDiv”).innerHTML = “User name OK”;


                                  document.getElementById(“ResultDiv”).innerHTML = “User name Already in Databse<br/> Choose a different one.”;







Now we will create our background page searchuser.php, which will search the user name from the data we pass to it.




//1. Conenct to Databae Here


//2. Select the Database


//Check if the user name variable is set or not as without it we cannot search





            // Build the query string

            $name = $_REQUEST[‘username’];


            $query = “SELECT user_name FROM tbl_user WHERE user_name = ‘{$name}'”;


            // Now fire the query


            $result = mysql_query($query);


            if(mysql_num_rows($result) > 0){

                        //User found


                        echo “OK”;



                        //User NOT found


                        echo “NF”;




            echo “ERROR”;






Now this page will search the user name in the background and outputs specified string, which will send back the Client to process as per requirement.



And now we require one more page before we proceed to Test.



This page is the main page of our application from where user creation is done. I have used only one element to demonstrate the AJAX technology; you can use it anywhere you like.


Name of the file: AddUser.html


<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>




<META NAME=”Generator” CONTENT=”EditPlus”>


<META NAME=”Keywords” CONTENT=””>

<META NAME=”Description” CONTENT=””>

<script type=”text/javascript” src=”js/ServerReq.js”></script>

<script type=”text/javascript” src=”js/SendAjaxRequest.js”></script>

<script type=”text/javascript”>

function checkUserName(){

            user =  document.getElementById(“username”);

          if(null == user or user.value == “”){

            alert(“Please enter a User Name to check “);









<form method=”POST”>

User Name : <input type=”text” name=”username” id=”username”/>

<a href=”#” onlcick=”javascript:checkUserName()”> check user name </a><br/>

<div id=”ResultDiv”></div><br/>

Password : <input type=”password” name=”pass” id=”pass” /> <br/>

Confirm Password : <input type=”password” name=”confpass” id=”confpass” /> <br/>


<input type=”submit” name=”submit” value=”Add user”/>







Here if the users click on the “check user name” link, the function will be called and JavaScript will send the request to the server in the background. In the mean time users can proceed filling the form. This form will be ready.


When the response data comes back from the server it will be displayed in the Div.


Also, Do not forget to add this JavaScripts at the TOP:


<script type=”text/javascript” src=”js/ServerReq.js“></script>

<script type=”text/javascript” src=”js/SendAjaxRequest.js“></script>


You can note from these above lines that the Scripts are located in the js folder under the root directory.


Important: As ServerReq.js holds the necessary functions to create and use the XMLHTTPRequest object then you always need to include the script ServerReq.js before using the Object.


HappY AjAxing 😉