Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 257
A_AR Avatar asked Mar 21 '13 06:03

A_AR


People also ask

How do I find my SQL Server connection string?

Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.


2 Answers

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());
like image 63
Praveen Nambiar Avatar answered Oct 10 '22 14:10

Praveen Nambiar


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);
like image 8
p.s.w.g Avatar answered Oct 10 '22 12:10

p.s.w.g