在winform中我试图将返回的数据集值与定义的值进行比较,但是我收到了以下错误。
在下面的代码中,我将字符串从listbox传递给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;
}
}
}
在数据库中,“数量”是字符串格式。
答案 0 :(得分: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;
}
答案 1 :(得分:1)
GetStock
方法返回DataSet
,但您需要实际的int
值。试试这个:
Convert.ToInt32(GetStock(listBoxItem.ToString()).Tables["Product"].Rows[0]["Quantity"])
答案 2 :(得分: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");
}