我打開Northwind數據庫中的一個數據庫查詢,以查看我的ShoppingCart包含的每個項目。從Products
表中取出ProductID
和UnitsInStock
。從數據庫中取出兩列以將數據保存到DataTabel ds
之後。然後比較以確保用戶輸入的數量小於數據庫中的庫存欄數量。爲什麼我在DataSet上得到一個NullReferenceException?
theCart.Values
是ICollections的一部分。
我gettign錯誤:從我的異常消息:「有連接到數據庫的一個問題:不設置到對象的實例對象引用」
這是代碼。
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection((string)Application["DBConnectionString"]);
foreach (OrderItem item in theCart.Values)
{
string selectionString =
"SELECT Products.ProductID, Products.UnitsInStock " +
"FROM Products" +
"WHERE Products.ProductID = " + item.ProductID + ";";
try
{
OleDbCommand cm = new OleDbCommand(selectionString, conn);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cm;
da.Fill(ds);
da.Dispose();
if (ds.Tables["Products"].Columns.Count != 0 &&
ds.Tables["Products"].Rows.Count != 0)
{
for (int index = 0; index < ds.Tables["Products"].Rows.Count; index++)
{
if (item.ProductID == int.Parse(ds.Tables["Products"].Rows[index][indexOfProductID].ToString()))
{
if (item.QuantityOrdered > int.Parse(ds.Tables["Products"].Rows[index][indexOfUnitsInStock].ToString()))
{
hasStock = false;
int inStock = int.Parse(ds.Tables["Products"].Rows[index][indexOfUnitsInStock].ToString());
txtUnderstockedItems.Text += "Sorry we do not have enough stock of item: " + item.ProductName +
"<br> Currently, " + item.ProductName + " (ID:" + item.ProductID + ") has " + inStock + " in stock.";
}
else
{//can output how many items in stock here.
hasStock = true;
}
}
}
}
catch (Exception ex)
{
txtUnderstockedItems.Text = "There was a problem connecting to the database: " + ex.Message;
}
finally
{
conn.Close();
}
}
}
你的權利,它是空的 – GivenPie
我會用適當的if語句編輯。 – evanmcdonnal
我之前沒有運行它,因爲我關閉了數據庫,然後運行if語句。現在,我可以在將它放入'try'塊後運行我的if語句 – GivenPie