asp.net


Connection Closing error


i have two DataReader in this code and vs give me this error "The connection was not closed. The connection's current state is open." the errors come from connection2 . i look at my code but my two connection was closed . where is the problem?
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection1 = DBConnection.getConnection())
{
string strquery1 = " with distinctvalueyes (typearticle) as (select top 1 'Fruit' FROM WeedingSalonGeneralRes where Fruit=1 union all select top 1 'Drink' FROM WeedingSalonGeneralRes where Drink=1 union all select top 1 'Desert' FROM WeedingSalonGeneralRes where Desert=1 union all select top 1 'MainFood' FROM WeedingSalonGeneralRes where MainFood=1 union all select top 1 'Salad' FROM WeedingSalonGeneralRes where Salad=1 union all select top 1 'TableFlower' FROM WeedingSalonGeneralRes where TableFlower=1 union all select top 1 'SaloonLighting' FROM WeedingSalonGeneralRes where SaloonLighting=1 union all select top 1 'Saloondesign' FROM WeedingSalonGeneralRes where Saloondesign=1 union all select top 1 'SloonCrew' FROM WeedingSalonGeneralRes where SloonCrew=1 union all select top 1 'Pastry' FROM WeedingSalonGeneralRes where Pastry=1 union all select top 1 'GiftCard' FROM WeedingSalonGeneralRes where GiftCard=1 ) select * from distinctvalueyes ";
connection1.Open();
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = connection1;
cmd1.CommandText = strquery1;
string cis = Session["customerID"].ToString();
lbl2_customerid.Text = cis;
SqlDataReader reader = cmd1.ExecuteReader();
if (reader.Read())
{
lbl8_fruit.Text = reader[0].ToString();
// wrapped in a using block, connection will now always be closed and disposed
using (SqlConnection connection2 = DBConnection.getConnection())
{
//query for fetch service prices
string strquery2 = "SELECT Fruit_price,Drink_price,Desert_price,MainFood_price,Salad_price,TableFlower_price,SaloonLighting_price,SaloonDesign_price,SaloonCrew_price,Pastry_price,GiftCard_price FROM GenReservationServicePrice";
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection2;
cmd2.CommandText = strquery2;
SqlDataReader reader2 = cmd2.ExecuteReader();
if (reader2.Read())
{
string Fruit_price;
string Drink_price;
string Desert_price;
string MainFood_price;
string Salad_price;
string TableFlower_price;
string SaloonLighting_price;
string SaloonDesign_price;
string SaloonCrew_price;
string Pastry_price;
string GiftCard_price;
Fruit_price = reader[0].ToString();
Drink_price = reader[1].ToString();
Desert_price = reader[2].ToString();
MainFood_price = reader[3].ToString();
Salad_price = reader[4].ToString();
TableFlower_price = reader[5].ToString();
SaloonLighting_price = reader[6].ToString();
SaloonDesign_price = reader[7].ToString();
SaloonCrew_price = reader[8].ToString();
Pastry_price = reader[9].ToString();
GiftCard_price = reader[10].ToString();
lbl8_fruit.Text = Fruit_price;
}
}
}
}
}
///connection class
public class DBConnection
{
private static SqlConnection connection=null;
public DBConnection()
{
}
public static SqlConnection getConnection()
{
if (connection != null)
{ return connection; }
else
{
String connectionString = WebConfigurationManager.AppSettings["connectionString"];
connection = new SqlConnection(connectionString);
return connection;
}
}
}
Edit
The problem is you are trying to use the same SqlConnection instance in 2 places. You should be using a new SqlConnection every time you need one.
Create it
Use it
Dispose it
Code change:
///connection class
public class DBConnection
{
public static SqlConnection getConnection()
{
String connectionString = WebConfigurationManager.AppSettings["connectionString"];
return new SqlConnection(connectionString);
}
}
Sql Server has something called Connection Pooling and this is enabled by default. Creating a connection in c# reuses the already available connections on Sql Server so this act is very cheap. Wrap all the code that uses the SqlConnections in using blocks to ensure that they are always closed so you do not have a connection leak.
Also the app.config / web.config has a ConnectionString section. You should use that instead of the app settings.
using SqlConnection
You should wrap all your SqlConnection instances in using blocks. This will ensure that the connection is always closed and released even if exceptions occur. It takes all the checking work out of your code too, no need to see if it was opened or not at close time.
Here is your code changed with the using blocks, I removed some of your logic so it is clear what I had changed.
protected void Page_Load(object sender, EventArgs e)
{
/* your existing code removed for clarit */
// wrapped in a using block, connection will now always be closed and disposed
using(SqlConnection connection1 = DBConnection.getConnection())
{
connection1.Open();
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = connection1;
cmd1.CommandText = strquery1;
string cis = Session["customerID"].ToString();
lbl2_customerid.Text = cis;
SqlDataReader reader = cmd1.ExecuteReader();
if (reader.Read())
{
/* your existing code removed for clarit */
// wrapped in a using block, connection will now always be closed and disposed
using(SqlConnection connection2 = DBConnection.getConnection())
{
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection2;
cmd2.CommandText = strquery2;
SqlDataReader reader2 = cmd2.ExecuteReader();
if (reader2.Read())
{
/* your existing code removed for clarit */
}
}
}
}
}

Related Links

How do I add asp tags using xmldocument?
Adding Areas to a hybrid MVC-Webforms application
Insert literal control inside HEAD when <head runat=“server”> is not specified?
Access database is randomly not updating and the ASP.Net page is losing the changes
Orchard CMS vs Sitefinity CMS
ASP.NET web self-maintainer as alternative to Windows service or SQL Agent
Forms Authentication Between IIS6 and IIS7 Servers
Large Editable grid in MVC
moving data from html to sql using asp.net
No connection could be made because the target machine actively refused it
ASP.NET Passing Inconsistent DateTime Format to SQL Server
LINQ Average function arguments
what is the best way to get live data from serial port and save it in SQL database?
Windsor composite lifestyle for asp.net process
Windows Azure Can I run multiple WebSites on the same Extra small instance or Small instance [closed]
How to auto-scroll to the bottom of a DevExpress.Web.ASPxHtmlEditor control?

Categories

HOME
airflow
grizzly
optimization
pyspark
cxf
popover
gap-system
conceptual
hex
localhost
opacity
install
jquery-select2
restheart
angularjs-ng-repeat
coding-style
openbsd
jpql
saucelabs
yui
swift3.1
react-select
google-closure-compiler
luis
greensock
android-actionbar
hapijs
views
legend-properties
project-structure
xna
mattermost
sha
visual-studio-community
proof-general
uibarbuttonitem
typeorm
cqlsh
visual-studio-debugging
directions
tunnel
javafxports
android-databinding
latency
ng-lightning
server-side-swift
sknode
electron-packager
compiler-warnings
android-doze-and-standby
spring-webflow-2
beanshell
sharpssh
aot
zedgraph
scrollmagic
cardview
racket-student-languages
mavlink
strtol
alfred
phpdesigner
innertext
chomsky-normal-form
jsondoc
sqldataadapter
dday
ewam
overlapping
transbase
vensim
p4python
page-refresh
applinks
alpha-beta-pruning
system.io.packaging
qf-test
winrun4j
opencobol
azure-caching
carrier
nativequery
nomachine
mdp
xcode5.1
mandelbrot
wpd
pymel
expresso-store
php-gettext
code-organization
cgaffinetransform
soapexception
nbehave
netbeans7.0
pitch-shifting
dongle
pkcs#7
atmega16

Resources

Encrypt Message