Array index

  • Thread starter Thread starter Ben
  • Start date Start date
B

Ben

I am having a problem with a web service I've created getting an "
Index was outside the bounds of the array." when I try to get the
value of ET.TerritoryName below. I've verified the length of ET is
4 after reallocating the dynamic array and the error happens when i =
0 so the first iteration of the loop. Does anyone have any idea what
the problem is? I know it's something simple I'm just not seeing.

EventTotalDS[] ET = null;
cnn.Open();

SqlCommand cmd = new SqlCommand("BP_SREventTotals", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@p_ContactGUID", SqlDbType.UniqueIdentifier).Value
= ContactGUID;

SqlDataAdapter oDA = new SqlDataAdapter(cmd);
DataSet oDS = new DataSet();

oDA.Fill(oDS,"EventTotals");

ET = new EventTotalDS[oDS.Tables["EventTotals"].Rows.Count + 1];

int i = 0;
foreach(DataRow dtRow in oDS.Tables["EventTotals"].Rows)
{
ET.TerritoryName = dtRow["TerritoryName"].ToString();
//above line gets index error on the left hand side
i++;
}
 
You have allocated the array for the EventTotalDS "references", but you have
not actually allocated the EventTotalDS objects themselves.

So you have allocated say 4 "slots" to hold EventTotalDS "pointers", but
each of those slots is initially empty (null).

That's why it crashes on the first index (0).

So put something like:

ET[ i ] = new EventTotalDS( );
before
ET.TerritoryName = dtRow["TerritoryName"].ToString();

Kevin
 
Ben said:
That was exactly it! It always helps to have an extra set of eyes.
Thank you very much.

That doesn't explain why you were getting an
ArrayIndexOutOfBoundsException though. You should have been getting a
NullReferenceException.
 
That doesn't explain why you were getting an
ArrayIndexOutOfBoundsException though. You should have been getting a
NullReferenceException.

This was in a web service and that was the error it was returning.
After I posted this thread I pulled the code out to a windows app to
test and started getting "object reference not set to an instance of
an object". I'm not sure why the web service returned the index error
which is why I had a hard time finding the problem.
 
Back
Top