3

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

enter image description here

4
  • 3
    In this case, it means your table is empty. And do yourself a favor and look into parameterized queries. Commented Feb 21, 2013 at 13:37
  • Put a break point in the code and see where you are getting the exception. If you are getting an index out of range, it tends to mean you are accessing an array with a number greater than it Length. Commented Feb 21, 2013 at 13:37
  • listBox1.GetItemText(listBox1.SelectedItem) is coming as null not sure why Commented Feb 21, 2013 at 13:42
  • Note I think your problem is with listBox.GetItemText(listbox.SelectedItem). Why don't you use this instead ListBox1.SelectedValue.ToString(); Commented Feb 21, 2013 at 13:42

5 Answers 5

1

Either there are no tables or no rows in your result set. This mean accessing the first entry (index 0) won't work, because there is no first entry. You get an IndexOutOfRangeException. Check your request and your data source.

Sign up to request clarification or add additional context in comments.

1 Comment

but it works for add method perfectly, why not for subtract, as i am passing items name as string from both method
1

This is failing because searchForPrice isn't returning any rows in the table. Hence the error

There is no row at position 0.

So, if you change the line to get a value from the list box, or somewhere else on the form, that will return data your error will be fixed.

The real underlying issue is the value being passed into searchForPrice.

Comments

0

The method searchforPrice is returning a dataset with no rows. So, Rows[0] doesn't exists. Check your method and adapt it to cases when searchforPrice returns no data (didn't find any price).

if (ds.Tables[0].Rows.Count != 0

{ ...}

Comments

0

The problem is because you dataset is returning 0 rows. That is because Item name is not passed to SQL query. You just need a minor change in your subPrice() function,

public int subPrice()
        {

            DataSet ds = searchforPrice(listBox1.SelectedItem.ToString());
            int sum;
            bool success = int.TryParse(maskedTextBox10.Text, out sum);
            int price = Convert.ToInt32(ds.Tables[0].Rows[0]["Price"]);
            return sum - price;

        }

4 Comments

Visual Studio doesnot recognise ListBoxItem
Just use listBox1.SelectedValue.ToString directly. If the selected item is of a complex object then you can do ((CAST)ListBox.SelectedItem).THE_PROPERTY_YOU_NEED.
@Amrit If I were you I would put a breakpoint and see what listbox.selectedItem and selectedvalue is in the quick watch window. The scenarios we have given you should work, if they aren't then the only way to go forward is to see what you are getting from those property.
0

The code that has been supplied should work.

You need to check that the columns in your actual datasource match what is being passed via your ListBox Items. It appears to me that you more than likely have a discrepancy in your naming convention.

If the Column Names being passed via ListBox match those in your datasource then the following code should work:-

public int subPrice()
        {
            if (listBox1.SelectedItems.Count > 0)
            {
                string SearchString = listBox1.SelectedItem.ToString().Trim();
                DataSet ds = searchforPrice(SearchString);

                if (ds.Tables["Product"].Rows.Count > 0)
                {
                    bool success = int.TryParse(maskedTextBox10.Text, out sum);
                    int price = Convert.ToInt32(ds.Tables["Product"].Rows[0]["Price"]);
                    return sum - price;
                }                
            }

          return null;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.