This is simply because you are trying to open a connection to the bank when it is already open.
See the example below.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace stackoverflow
{
public partial class ConexaoAberta : System.Web.UI.Page
{
protected String ConnString
{
get
{
return ConfigurationManager.ConnectionStrings["DBConn"].ToString();
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConnString;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable dt = new DataTable();
StringBuilder query = new StringBuilder();
query.Append("SELECT * FROM [stackoverflow].[dbo].[Categoria]");
conn.Open();
adapter.SelectCommand = new SqlCommand(query.ToString(), conn);
adapter.Fill(dt);
GetSubCategoria(conn);
}
public void GetSubCategoria(SqlConnection conn)
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable dt = new DataTable();
StringBuilder query = new StringBuilder();
query.Append("SELECT * FROM [stackoverflow].[dbo].[SubCategoria]");
conn.Open(); // Aqui você tenta abri novamente a conexão, sendo que o método acima não tinha
// fechado ela.
adapter.SelectCommand = new SqlCommand(query.ToString(), conn);
adapter.Fill(dt);
}
}
}
In the last method public void GetSubCategoria(SqlConnection conn)
, I can my connection and having it open again conn.Open();
, with the current status being open generating the error.
Certainlyyourerrorisbeinggeneratedwhenyouattempttoenteryourdata.
Makesuretheconnectionstatusisopen,themostadvisablewouldbetowrapallyourconnectionsinblocks.
using .
using (var conn = new SqlConnection(_dbconnstr))
{
//code
}
Or try finally .
SqlConnection conn = new SqlConnection(_dbconnstr);
try
{
//code
}
finally
{
conn.Dispose();
}