tags:

views:

61

answers:

2

I am getting an error that an open DataReader associated with this Command, when I'm not using datareader(though probably executereader() is the same thing) how would I close this if I don't have a datareader present?

using (SqlConnection conn = new SqlConnection(ConnectionString))
{
  SqlCommand cmd = new SqlCommand("spSelectAllTypes",conn);
  cmd.CommandType = CommandType.StoredProcedure;
  SqlCommand cmd1 = new SqlCommand("spSelectAllTripA", conn);
  cmd1.CommandType = CommandType.StoredProcedure;

  conn.Open();

  //checkboxlist
  cbTransportType.DataSource = cmd.ExecuteReader();
  cbTransportType.DataBind();

  //dropdownlist
  ddlTripTypeA.DataSource = cmd1.ExecuteReader();
  ddlTripTypeA.DataTextField = "TripType";
  ddlTripTypeA.DataValueField = "TripTypeID";
  ddlTripTypeA.DataBind();

}

I just want to be able to databind a bunch of dropdownlist in one open connection. (before I had multiple open and closes for each control)

+1  A: 

ExecuteReader will return an open data reader. You should really dispose that before the connection closes, however I'm not sure how that would look with regards to you using it as a data source.

Adam
@Adam, Ideally you should not be using datareader directly as a data source.
Giorgi
@Giorgi what should I use?
Spooks
oh okay, gotcha!
Spooks
@Adam, I didn't mean that you are using it. I said it in general.
Giorgi
A: 

I think I found a work around, let me know if this is okay coding...

 using (SqlConnection conn = new SqlConnection(ConnectionString))
  {
     SqlCommand cmd1 = new SqlCommand("spSelectAllTypeA", conn);
                 cmd1.CommandType = CommandType.StoredProcedure;
     SqlCommand cmd2 = new SqlCommand("spSelectAllTypeB", conn);

conn.Open();

    setDDL(ref ddlTripTypeA, cmd1, "Type", "pkiTypeAID");

    setDDL(ref ddlTripTypeB, cmd2, "Type", "pkiTypeBID");
}
    ..end of method..

    protected void setDDL( ref DropDownList ddl, SqlCommand cmd, string textField, string valueField)
        {
            SqlDataReader reader = cmd.ExecuteReader();
            ddl.DataSource = reader;
            ddl.DataTextField = textField;
            ddl.DataValueField = valueField;
            ddl.DataBind();
            reader.Close();
        }

Works great for populating dropdownlist, I suppose I could make it more generic for every control.. thoughts?

Spooks
The code for your first method isn't reusable.Why must you use a DataReader? Working with DataSets/DataTables is much easier than passing around a DropDownList reference, for example. But the is just my preference.
TheGeekYouNeed
I guess I don't need a datareader. Is it less resources to use datasets? - not sure what you mean by not reusable... should I make it its own class, for now its only for dropdownlist, i guess instead I could have it pass a control, then depending on the control do different things
Spooks