billz billz - 1 month ago 6
ASP.NET (C#) Question

IndexOutOfRangeException when button is clicked

I'm making a simple shopping cart. which adds product to the shopping cart page from a button which is at another page my add to cart button is as follows

protected void addCart_Click(object sender, EventArgs e)
{
if (Session["mySC"] == null)
{
mySC = new CartClass();
Session["mySC"] = mySC;

}

string ID = Request.QueryString["ID"];
mySC = (CartClass)Session["mySC"];
DataTable dt = DA.selectQuery("Select * from Trees where ID='"+ID+"'");
DataRow row = dt.Rows[0];
mySC.insert(new cartItems(Int32.Parse(ID),
row["TreeName"].ToString(),
row["Image"].ToString(),
Double.Parse(row["PricePerCube"].ToString()), 1));


}
}


when this button is being clicked the following error pops up

An exception of type
System.IndexOutOfRangeException
occurred in
System.Data.dll
but was not handled in user code

Additional information: There is no row at position 0.

any help would be appreciated

Answer
DataRow row = dt.Rows[0];

Will throw exception if no rows returned. Add an if condition before it

If (dt.Rows.Count > 0){

DataRow row = dt.Rows[0];
            mySC.insert(new   cartItems(Int32.Parse(ID),
                row["TreeName"].ToString(),
                row["Image"].ToString(),
                    Double.Parse(row["PricePerCube"].ToString()), 1));



}