2

winform では、返されたデータセット値を定義された値と比較しようとしていますが、次のエラーが発生しています。

ビジュアル スタジオ エラー

以下のコードでは、文字列をリスト ボックスから GetStock メソッドに渡しています。

public bool checkStock()
        {
            foreach (var listBoxItem in listBox1.Items)
            {
                if (Convert.ToInt32(GetStock(listBoxItem.ToString())) == 0)
                {
                    MessageBox.Show(listBoxItem.ToString() + " not in Stock!. Please delete the item before proceeding");
                    return false;
                }
            }
            return true;
        }

GetStock() のコード

 public DataSet GetStock(string product)
        {
            DataSet dataSet = new DataSet();
            OleDbConnection oleConn = new OleDbConnection(connString);

            try
            {
                oleConn.Open();
                string sql = "SELECT [Quantity] FROM [Product] WHERE [Product Name]='" + product + "'";
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
                dataAdapter.Fill(dataSet, "Product");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                oleConn.Close();
            }
            if (dataSet.Tables["Product"].Rows.Count <= 0)
                return null;

            return dataSet;
        }

    }
}

データベースでは、「数量」は文字列形式です。

4

3 に答える 3

4

GetStockを返しますが、DataSetに渡していますConvert.ToInt32

if (Convert.ToInt32(GetStock(listBoxItem.ToString())) == 0)

おそらく次のようなものが必要です。

int stockCount = GetStockQuantity(listBoxItem.ToString());
if (stockCount == 0)
{
    MessageBox.Show(listBoxItem.ToString() + " not in Stock!. Please delete the item before proceeding");
}

これが変更された方法です(パラメーターを使用していることに注意してください)

public int GetStockQuantity(string product)
{
    int quantity = 0;
    string sql = "SELECT TOP 1 [Quantity] FROM [Product] WHERE [Product Name] = ?";
    using(var oleConn = new OleDbConnection(connString))
    using(var cmd = new OleDbCommand(sql , oleConn))
    {
        cmd.Parameters.AddWithValue("?", product);
        try
        {
            oleConn.Open();
            object obj_quantity = cmd.ExecuteScalar();
            if(obj_quantity != null)
                // "In database the "Quantity" is in string format." 
                // Change it to int if possible
                int.Parse((string)obj_quantity);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
    return quantity;
}
于 2013-03-01T12:21:14.743 に答える
1

GetStockメソッドは を返しますが、実際の値DataSetが必要です。intこれを試して:

Convert.ToInt32(GetStock(listBoxItem.ToString()).Tables["Product"].Rows[0]["Quantity"])
于 2013-03-01T12:22:54.593 に答える
0

この方法を試してください:

var count = GetStock(listBoxItem.ToString());

if (count > 0)
{
  //TODO: other stuff
}
else
{
   MessageBox.Show(listBoxItem.ToString() + " not in Stock!. Please delete the item before proceeding");
}
于 2013-03-01T12:25:19.250 に答える