Connectionstring from web.config file




















In the following code you can see I have used the GetConnectionstring method of the ConnectionString class and passed the keyname to connect to the specific database using keyname. If you got this error when reading a connection string from a web.

Using the preceding described way you can connect to the database using this method, there is no need to write a connection code in every page. Now we will see the next way to specify a connection. Now I will create a common class file with connection code. I have created a DBConnectionClass. You can use this class file in multiple Web applications where you need to use the same database connection.

In this class I declared an enum for the list of the database. We can specify all the database names to be used across application and access them using an enum.

Then I wrote a method, GetConnectionstring, with Database enum parameter. Write the following code in your class:. Then I will describe how to access this class method in a web page. You can call this method as in DBConnectionClass. Getconnectionstring DBConnectionClass. In the same way you saw in the web.

In the same way I already described, for the web application you can read a connection from the app. I have a web service with a web. There are no other connection strings in the config file at all. When i use the following line to get a particular connection string i get a null reference exception:. When I loop through my connection string collection i only see 1 connection string, and it is named LocalSqlServer:.

GetEnumerator ;. WriteLine csc[i]. Here's the catch, i don't have a LocalSqlServer connection string in my web. I figured it out. I did not give any of you enough of the contextual information on how i was testing for you to help me figure this out and i apologize. I was testing in the debugger with TestDriven. NET and when i do that i end up defaulting to the. Then include the namespace System.

Configuration to get access to the ConfigurationManager class. Configuration files are hierarchical, with machine. You can clear connection strings defined earlier in the hierarchy to make sure any unwanted settings don't bubble down to your desired value.

Use this information only for old. NET 1. In the appSettings location, add a key named whatever you like to reference your connection string to.



0コメント