在我的winform中,我试图通过传递物品的名称从数据库中获取该物品的价格。用户可以在下拉框中看到从数据库中读取的物品。当用户选择一个物品并点击“添加”时,它会将该特定物品添加到数据库中。
同时,当用户添加物品时,其中一个文本框会添加价格。如果用户添加了五个物品,则文本框会显示五个物品价格的总和。到这里为止一切正常。
现在,当用户想要从列表框中删除物品时,用户选择该物品并单击“删除物品”,Visual Studio会抛出“索引超出范围”的错误。
我在添加方法和减法方法中使用相同的代码来获取价格,但不确定为什么只有添加方法有效而减法无效。 添加价格的代码:
同时,当用户添加物品时,其中一个文本框会添加价格。如果用户添加了五个物品,则文本框会显示五个物品价格的总和。到这里为止一切正常。
现在,当用户想要从列表框中删除物品时,用户选择该物品并单击“删除物品”,Visual Studio会抛出“索引超出范围”的错误。
我在添加方法和减法方法中使用相同的代码来获取价格,但不确定为什么只有添加方法有效而减法无效。 添加价格的代码:
public int addPrice()
{
DataSet ds = searchforPrice(comboBox2.Text);
int sum;
bool success = int.TryParse(maskedTextBox10.Text, out sum);
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["Price"]);
return sum + price;
}
减去价格的代码
public int subPrice()
{
DataSet ds = searchforPrice(listBox1.GetItemText(listBox1.SelectedItem));
int sum;
bool success = int.TryParse(maskedTextBox10.Text, out sum);
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["Price"]);
return sum - price;
}
从数据库获取价格的代码
public DataSet searchforPrice(string itemName)
{
DataSet dataSet = new DataSet();
// Create connection object
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT [Price] FROM [Product] WHERE [Product Name] ='" + itemName + "'";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Product");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
return dataSet;
}