2

在 winform 中,我试图将返回的数据集值与定义的值进行比较,但出现以下错误。

Visual Studio 错误

在下面的代码中,我将字符串从列表框传递给 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返回 aDataSet但您将其传递给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方法返回 a 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 回答