Thursday, March 8, 2012

cant retrieve connection string from web.config - ASP.NET 2.0

All,

I don't know what is the problem, i am not able to retrieve connection string from web.config in my code behind page

I used every solution provided by people in differents forums.

can anybody help me with this.

I used

WebConfigurationManager.OpenWebConfiguration("/TimeSheetApplication").ConnectionStrings("TimeSheetConnectionString").ConnectionString;

WebConfigurationManager.ConnectionStrings("TConnectionString").ConnectionString;

Here is a reference on MSDN

http://msdn2.microsoft.com/en-us/library/system.web.configuration.webconfigurationmanager(VS.80).aspx

or you can post your web.config with above code and let me look

|||

My code

Web.Config -

<connectionStrings>

<addname="TConnectionString"connectionString="Data Source=Source name"

providerName="System.Data.SqlClient" />

</connectionStrings>

Code Behind -

string query ="Select * from table"

string myConnectionString = ??

SqlConnection myConnection =newSqlConnection(myConnectionString);

SqlDataAdapter ad =newSqlDataAdapter(query, myConnection);

DataSet ds =newDataSet();

ad.Fill(ds,"table");

GridView1.DataSource = ds;

GridView1.DataBind();

? - When i used

ConnectionStringSettingsCollection connectionStrings =WebConfigurationManager.ConnectionStringsas ConnectionStringSettingsCollection;

connectionStrings["TConnectionString"].Name

it gives error

Cannot apply indexing with [] to an expression of type 'ConnectionStringSettingsCollection'

The type 'System.Configuration.ConnectionStringSettingsCollection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

|||

You can access this way

string connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["TConnectionString"].ToString();

|||

Thanks Farooq...

However i used the same code earlier and i am getting the error

Cannot apply indexing with [] to an expression of type 'ConnectionStringSettingsCollection'

The type 'System.Configuration.ConnectionStringSettingsCollection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

|||

make sure you have this element in web.config:

<system.web>

<compilation>

<assemblies>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblies>

</compilation>

</system.web>

No comments:

Post a Comment