在我的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;
}
代码for substract 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;
}
在这种情况下,这意味着你的表是空的。并帮助你一个忙,并看看参数化的查询。 – 2013-02-21 13:37:05
在代码中放置一个断点,看看你在哪里得到异常。如果你得到的索引超出范围,它往往意味着你正在访问一个数组大于它的长度的数组。 – TYY 2013-02-21 13:37:56
listBox1.GetItemText(listBox1.SelectedItem)即将作为null不知道为什么 – 2013-02-21 13:42:36