C# - SPLessons

Read connection string from web.config

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Read connection string from web.config

Read connection string from web.config


Hi Every one, today we are going to learning how to read connection string from web.config file.

Step 1: Here we have connection string in web config file.

  // Web.config

<?xml version="1.0"?>
        <add name="publichealthConnectionString" connectionString="Data Source=SPLESSONS\SQLEXPRESS;Initial Catalog=publichealth;Integrated Security=True"
            providerName="System.Data.SqlClient" />


Step 2: Add System.Configuration reference to your program.

Step 3: Use the connection like bellow :

String customconnectionString =  ConfigurationManager.ConnectionStrings["publichealthConnectionString"].ConnectionString;

                string sql = "insert into patient(name) values (@name)";
                using (SqlConnection conn = new SqlConnection(customconnectionString))
                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                        cmd.Parameters.AddWithValue("@name", firstname); // assign value to parameter
            catch (SqlException ex)
                string msg = "Insert Error:";
                msg += ex.Message;