Question

I have a for loop that I use to get the list item for displaying in my line graph. It's very simple but I get an index is out of range error. The way I understand what happens in the for loop is as long as the i is less then the indexCount() it keeps counting. Why is mine going past my index method? I have researched and used breakpoint found nothing and i = my collection size.

List<ChartData> points = ChartData.getData();
    for (int i = 0; i < chartData.indexCount(); i++)
    {
        series0.AddItem(points[i].Produced);
        series1.AddItem(points[i].Labeled);
        RadChart1.PlotArea.XAxis.Items.Add(new ChartAxisItem(points[i].CasesLabeled.ToString()));
    }

I made a custom index so that I would be able to get most of the rows form the database for display. hence the chartData.indexCount() method there. Here is my indexCount method maybe something went wrong here?

public int indexCount()
{

    StringBuilder sqlString = new StringBuilder();
    sqlString.Append("SELECT Count(Number) FROM SomeDB.dbo.Order");

    SqlDataReader reader = null;
    SqlConnection dbConn = DBHelper.getConnection();

    try
    {
        reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), null);
        if (reader != null)
        {
            while (reader.Read())
            {
                number = reader.GetInt32(0);
            }
        }
        reader.Close();
        reader.Dispose();
        dbConn.Close();
        dbConn.Dispose();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return number;
}
Was it helpful?

Solution

First, I would recommend to use ExecutrScalar instead of ExecuteReader.

Second, you have the list of point - and that list know how much items it has (the Count property).... At least use Math.Min to make sure you're not overflowing your list.

And just as a good advice - don't close the reader object (or any object which implement IDisposable). Instead, declare the object in using statement:

using (reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), null))  
{
    // code which using reader 
} 

And lastly - don't call indexCount on every iteration... Just save its result to a variable...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top