In my winform, i am trying to get the price of an item from database by passing item's Name. User can see items in the combo box which populates item from the database. When user selects item from combo box and clicks add, it add that particulat item to the database.
In the mean time when user adds the item, one of the text box adds the price. If user adds five items the textbox shows the sum of five item price. till here everything is working fine.
Now when user wants to remove the item from the listbox, user selects the item and click on delete item , visual studio throws the error "Index out out of range".
I am using same code for getting price for both add method and substract method but not sure why only add method works and not the substract
Code to Add Price
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;
}
Code 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;
}
Code for getting Price from Database
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;
}
