Search code examples
c#asp.netexecutereaderdbcommand

ExecuteReader: Connection error message


I would like to display data in my text boxes and i have run across an error in my DAL. I have a stored procedure but i cannot get my data to return in the return value. I would like to use my BLL to return a DataTable. Please can you help?

DAL

public static string GetTicket(collection b)
        {
            try
            {

                string returnValue = string.Empty;
                DB = Connect();
                DBCommand = connection.Procedure("getTicket");
                DB.AddInParameter(DBCommand, "@SupportRef", DbType.String, b.SupportRef1);

                var myReader = DBCommand.ExecuteReader();
                while (myReader.Read())
                {
                    returnValue = myReader.GetString(0);
                }

                return returnValue;
            }

            catch (Exception ex)
            {
                throw ex;
            }

        }

I get the following error:

ExecuteReader: Connection property has not been initialized.

I am using a connection class which looks like this:

public class connection
{
    const string StrConnection = "TicketHelperConnectionString";
    internal static Database DB;
    public static DbCommand DBCommand;
    public static Database Connect()
    {

        try
        {
            DB = DatabaseFactory.CreateDatabase(StrConnection);
            return DB;
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
    public static DbCommand Procedure(string procedure)
    {

        try
        {
            DBCommand = DB.GetStoredProcCommand(procedure);
            return DBCommand;
        }
        catch (Exception ex)
        {
            throw (ex);            
        }
    }
}

Solution

  • Looks like the Connection property of DBCommand is not set, before you return the command from the Procedure method you have to set its connection property:

    DBCommand = DB.GetStoredProcCommand(procedure);
    
    // DBCommand.Connection = ...
    
    return DBCommand;