I have SqlDataReader that was sitting in a page’s code behind (well actually a web user control). I’d like to move this code to a separate class which the user control calls. But how do I bind the data from the class to the on page repeater?
Is this an acceptable concept?
Here’s my code moved to a class:
public class ShoppingCart
{
public ShoppingCart(int ShoppingCartHeadID)
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
conn = new SqlConnection(iceConns.iconn);
comm = new SqlCommand("Ordering.sl_ShoppingCartContents", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@shoppingCartHeadID", SqlDbType.Int));
comm.Parameters["@shoppingCartHeadID"].Value = ShoppingCartHeadID;
try
{
conn.Open();
reader = comm.ExecuteReader();
Cart.DataSource = reader; //This ain't gonna work!
if (reader.HasRows)
{
Cart.DataBind(); //This ain't gonna work!
varCartStatus = true;
}
reader.Close();
}
catch
{
//Error trapping
}
finally
{
conn.Close();
}
}
}
Any help would be greatly appreciated.
You should create an entity object for the returned data. Then you can bind any control to a List of the object you created.
Create a Cart object with the properties that map to your database table.
Then create a class like CartRepository that will have a method called GetCartById(CartId). This method will do the work above, but instead of trying to bind anything here you are simply going to fill your Cart objects. The return a list of those objects and you can bind that list to any control.
Now from your code just bind your control to the List returned from the repository object.