Home Asp.net How to Get ConnectionString from Web.config in Asp.net?

How to Get ConnectionString from Web.config in Asp.net?

23
0

Now here in this tutorial, I’ll explain how to read or get connectionstring from web.config file using c# as well as vb.net in Asp.net. Read the full tutorial to get a clear cut idea on how to obtain connectionstring from web.config file. If you feel that that the tutorial was worth your time, then please do check out our previous tutorials as well as I mentioned below.

In my previous tutorials, I’d explained about appSettings vs connectionStrings in web.config file, sql injection with example and other more amazing tutorials on connectionStrings, Asp.net here.

 

Get ConnectionString from Web.config File

Before starting how to read or get connectionstring from web.config file, you should know how to get connection string to connect your database from here that will show you also the difference why I’ve not used user id and password in my connection string. After knowing that, you can adjust your connection string in web.config as follows.

<connectionStrings>
   <add name=myDbConnectionproviderName=System.Data.SqlClient
   connectionString=Data Source=myServer;Integrated Security=true;Initial Catalog=myDatabase/>
</connectionStrings>

To read or get connectionstring from web.config file in asp.net, we need to add System.Configuration namespace that will help us to read our connection string.

Note: If you have defined your connection string under appSettings section, you can get your connectionstring from appSettings section this way.

Read Connectionstring in C#

protected void Page_Load(object sender, EventArgs e)
{
string con = System.Configuration.ConfigurationManager.ConnectionStrings[“myDbConnection”].ConnectionString;
}

Read Connectionstring in Vb.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim con As String = System.Configuration.ConfigurationManager.ConnectionStrings(“myDbConnection”).ConnectionString
End Sub

Example: Simple Insert, Update and Delete in Asp.net

That’s it, now you’ll be able get connectionstring from web.config file and can use wherever you want.

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!