I am creating a class in ASP.NET that accesses a database (this class is a login) but when executing it it shows me the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteScalar: The Connection property has not been initialized.
The complete code is as follows:
public class UserBusinessLogic
{
public int CheckUserLogin(ClsLogin User)
{
string conStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conObj = new SqlConnection(conStr);
SqlCommand comObj = new SqlCommand();
comObj.CommandType = CommandType.StoredProcedure;
SqlParameter Parameters = new SqlParameter();
Parameters = new SqlParameter();
Parameters.Direction = ParameterDirection.Input;
Parameters.SqlDbType = SqlDbType.VarChar;
Parameters.Size = 150;
Parameters.ParameterName = "@NombreUsuario";
Parameters.Value = User.NombreUsuario;
Parameters = new SqlParameter();
Parameters.Direction = ParameterDirection.Input;
Parameters.SqlDbType = SqlDbType.VarChar;
Parameters.Size = 20;
Parameters.ParameterName = "@Contrasena";
Parameters.Value = User.Contrasena;
conObj.Open();
return Convert.ToInt32(comObj.ExecuteScalar());
}
}
Your value to initialize the connection (
conStr
) is not correct or is empty:may be a reason why you get the error:
Also the other detail could be that you are not initializing the SqlCommand correctly:
You are not assigning the connection
conObj
to your objectSqlCommand comObj
.This should fix it:
It is clear that you do not assign in the object
SqlCommand
SqlConnection
but you could also reduce the code a lot if you define the parameters better.
I recommend you define the connection object inside a block
using
so the object is destroyed correctly and you let ado.net apply connection pooling to maintain the connections .