A_AR
A_AR

Reputation: 508

Getting sql connection string from web.config file

I am learning to write into a database from a textbox with the click of a button. I have specified the connection string to my NorthWind database in my web.config file. However I am not able to access the connection string in my code behind.

This is what I have tried.

protected void buttontb_click(object sender, EventArgs e)
{
    System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
    System.Configuration.ConnectionStringSettings constring;
    constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
    SqlConnection sql = new SqlConnection(constring);

    sql.Open();
    SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
    comm.ExecuteNonQuery();
    sql.Close();
}

I get a tooltip error for

SqlConnection sql = new SqlConnection(constring);

as

System.data.SqlClient.Sqlconnection.Sqlconnection(string) has some invalid arguments.

I want to load the connection string from the web.config in constring

Upvotes: 12

Views: 43728

Answers (4)

Praveen Nambiar
Praveen Nambiar

Reputation: 4892

You can simply give a Name to your ConnectionString in web.config file and do this:

web.config:

<add name="ConnectionStringName"  connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>

Code Behind:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());

Upvotes: 12

शेखर
शेखर

Reputation: 17614

I will suggests you to create a function rather than directly access the web.config file as follow

    public static string GetConfigurationValue(string pstrKey)
    {
        var configurationValue = ConfigurationManager.AppSettings[pstrKey];
        if (!string.IsNullOrWhiteSpace(configurationValue))
            return configurationValue;

        throw (new ApplicationException(
            "Configuration Tag is missing web.config. It should contain   <add key=\"" + pstrKey + "\" value=\"?\"/>"));

    }

And use this function in you application

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

That's because the ConnectionStrings collection is a collection of ConnectionStringSettings objects, but the SqlConnection constructor expects a string parameter. So you can't just pass in constring by itself.

Try this instead.

SqlConnection sql = new SqlConnection(constring.ConnectionString);

Upvotes: 8

Rajeev Kumar
Rajeev Kumar

Reputation: 4963

try this

readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());

Upvotes: 4

Related Questions