ShoppingCart が必要とする各アイテムについて、Northwind データベースからデータベース クエリを開いています。テーブルProductID
からUnitsInStock
出し入れすることです。Products
データベースから 2 つの列を取り出して、データをDataTabel ds
. 次に、ユーザーが入力した数量がデータベース内の列の在庫数よりも少ないことを確認します。
theCart.Values
ICollections の一部です。
「データベースへの接続に問題がありました: オブジェクト参照がオブジェクトのインスタンスに設定されていません。」という例外メッセージからエラーが発生しました。
これがコードです。
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();
}
}
}