Reputation: 478
My connection string, my database, and everything is working just fine, but just when I call it once at my page.
I have several methods that make connection to my database and return a value to me, and for the first time i need to use two of then. And i'm getting this error in conn.Open()
:
"The ConnectionString property has not been initialized." "Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code."
Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.
When i call just one is working great.
My source of two of this methods is, i'm using almost the same code for everyone, just changing the table name:
public DataTable Category(){
sda = new SqlDataAdapter("select * from tbl_category", conn);
sda.Fill(dt);
return dt;
}
and
public int CategoryLastId(){
using (conn){
conn.Open();
sqlCommand = new SqlCommand("SELECT MAX(Id) AS LastID FROM tbl_category", conn);
sqlCommand.ExecuteNonQuery();
Int32 newId = (Int32)sqlCommand.ExecuteScalar();
conn.Close();
return Convert.ToInt32(newId);
}
}
feels like they are in conflict(also, calling on .Get with NHibernate, but this also is working fine)
Upvotes: 2
Views: 7244
Reputation: 1102
The problem is that the using
statement is closing the connection when it returns.
Create the SqlConnection
inside your using statement as follows:
using (SqlConnection conn = new SqlConnection(connString)) { ... }
For getting the connection string from your config file:
connString = ConfigurationManager.ConnectionStrings["yourConnString"].ConnectionString;
The configuration file:
<connectionStrings>
<add name="yourConnString" connectionString="..." providerName="..."/>
</connectionStrings>
Upvotes: 5