How to add and access connection string from web.config

10,316

Solution 1

If you know the connection string name you can use the ConnectionStrings property of the ConfigurationManager class

E.g.

using System.Configuration;
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString.ToString();

Where, your web.config would contain a connectionstring named ConnectionStringName

Solution 2

Here is an Example of Creating and adding connectionString to the web.config for SQL Server you can change the sql Connection to OleDb connection

SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
        connectionStringBuilder.DataSource = "localhost";
        connectionStringBuilder.IntegratedSecurity = true;
        connectionStringBuilder.InitialCatalog = "SampleDB";

        ConnectionStringSettings connSttng = new ConnectionStringSettings();
        connSttng.Name = "ConnectionStringName";
        connSttng.ProviderName = "Providername";
        connSttng.ConnectionString = String.Format("DataSource={0};InitialCatalog={1};IntegratedSecurity={2}", connectionStringBuilder.DataSource, connectionStringBuilder.InitialCatalog, connectionStringBuilder.IntegratedSecurity);

        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        config.ConnectionStrings.ConnectionStrings.Add(connSttng);
        config.Save(ConfigurationSaveMode.Modified, true);
        ConfigurationManager.RefreshSection("connectionStrings");

Hope this will be use full

Solution 3

in web config:

<connectionStrings>
<add 
    name="NorthwindConnectionString"
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"/>
 </connectionStrings>

in view:

using System.Configuration;
string ConnectionString =ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.ToString();
Share:
10,316
Ishan
Author by

Ishan

Hello i am into ASP.net C#/ Sharepoint development and constantly learning in order to expertise in the field.

Updated on June 05, 2022

Comments

  • Ishan
    Ishan almost 2 years

    I want to add connection string to connect to mysql that are define in web.config file and access the same connection in my C# code how can I do this?

    Here is my code sample that run after onclick of a button to connect to database.

    protected void Button2_Click(object sender, EventArgs e)
        {
            String a = DropDownList1.SelectedItem.Value;
            String b = DropDownList3.SelectedItem.Value.PadLeft(3, '0');      
            String c = TextBox2.Text.PadLeft(5,'0').ToString();
            String d = TextBox3.Text.ToString();
            String digit = a+ b  + c + d;
            try
            {
             myConn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
             myConn.Open();
                //**
                string sql = "select * from testcase.main where reg_no =?";            
                //**
                OdbcCommand cmd = new OdbcCommand(sql, myConn);            
                //**
                cmd.Parameters.AddWithValue("?", digit);
                MyReader = cmd.ExecuteReader();
                //**
                while (MyReader.Read())
                {
                    String f = MyReader["pet_name"].ToString();
                    String g = MyReader["res_name"].ToString();
    
                    Label9.Visible = true;
                    Label9.Text = f;
    
                    Label10.Visible = true;
                    Label10.Text = "VS";
    
                    //Label11.Visible = true;
                    Label11.Text = g;
    
                }
    
                MyReader.Close();
            }
            catch (Exception e1)
            {
                Response.Write(e1.ToString());
            }
            finally
            {
                if (MyReader != null && !MyReader.IsClosed)
                {
                    MyReader.Close();   
                }
    
                if (myConn != null && myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                }
            }