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

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

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

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="myDbConnection" providerName="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: You may also like insert, update and delete on asp.net gridview which is real usecase of using connectionstring.

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

Previous articleDifference between appSettings and connectionStrings in Web.config
Next articleHow to Get appSettings Value from Web.config File?
Hi there, I am Mayank, the man behind Technical Mack. I started AspnetO with a motive to educate people on various programming languages ranging from beginners to expert level. Through this blog, I aim to provide more insightful content.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

19 − four =