assign values to array in a while loop

assign values to array in a while loop

Page 1 of 1

1 Replies - 11631 Views - Last Post: 19 September 2010 - 09:52 AM Rate Topic: -----

#1 whitekeeper   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 17-July 09

assign values to array in a while loop

Posted 19 September 2010 - 08:45 AM

Hi everyone, how is it possible to make the data from the database table be assign 1 by 1 into the array in order. So far i have tried a couple of other ways but it seems like the array either store 1 results into all 7 slots of the array or give me error "index out of range exception".

Please help me in this. Code is shown below.

//Array to store data
string[] time = new string[7];

SqlCeCommand pop = new SqlCeCommand("Select * From History", conn);
SqlCeDataReader dr = pop.ExecuteReader();

 while (dr.Read())
{
     //assign values gotten from database to the array 1 by 1
     time[ whatToPutHere? ] = dr["time_recorded"];

     //How do i assign values to the array dynamically? 
}




Is This A Good Question/Topic? 0
  • +

Replies To: assign values to array in a while loop

#2 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: assign values to array in a while loop

Posted 19 September 2010 - 09:52 AM

My first suggestion would be to use a List<string> instead of a string[]. Then you don't have to hard code a size, you can just add:

List<string> time = new List<string>();
...
while(dr.Read())
{
  time.Add(dr["time_recorded"]);
}


But if you would insist on using an array, all you have to do is use an index variable:

string[] time = new string[7];
...
int i = 0;
while (dr.Read())
{
     time[i] = dr["time_recorded"];
     ++i;
}


The problem with this approach is if there are more entries in the Reader than there are in the array, you will eventually attempt to put something at time[7], which doesn't exist, and will throw an IndexOutOfBoundsException.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1