gpt4 book ai didi

c# - 比较数据集值

转载 作者:行者123 更新时间:2023-12-02 05:12:45 24 4
gpt4 key购买 nike

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

Visual Studio Error

在下面的代码中,我将字符串从列表框传递给 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;
}

}
}

在数据库中,“数量”是字符串格式。

最佳答案

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;
}

关于c# - 比较数据集值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15157609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com