By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,728 Members | 2,462 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,728 IT Pros & Developers. It's quick & easy.

How can I add items to an array while the array's index is growing

JnrJnr
P: 88
I'm going to leave out most details so say for instance i have a combobox and when I select a car from the combobox I have a variable called Index that grows with each selection of the combobox. that variable is the index of my array called myArray. So when the combobox selects then the index of the array grows. There is also a SQL select statemant that retreives a value called myCar.

Expand|Select|Wrap|Line Numbers
  1. string[] myArray;
Expand|Select|Wrap|Line Numbers
  1. int Index;
private void Combobox_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand getCar = new SqlCommand("select Car from myTable where carID = '"+ 3 +"' ", myConnection);[/code]
[code]myCar = getCar.ExecuteNoneQuery();

Index ++;
myArray = new string[Index];
MyArray[Index] = myCar.ToString();
}

The array obviously gets all it's indexes but only the last index in the array has the value of myCar and the rest is null.
The reason is because I'm declaring the array over and over each time with the new keyword.

How can I keep all the 'myCars' in the Array everytime the array's index grows?

Your Help would be appreciated
Sep 20 '10 #1

✓ answered by Anton Zinchenko

Instead of creating a new array each time, use
Expand|Select|Wrap|Line Numbers
  1. Array.Resize(ref array, newsize)
. Or you can use a collection:

Expand|Select|Wrap|Line Numbers
  1. List<string> myCollection = new List<string>();
  2. private void Combobox_SelectedIndexChanged(object sender, EventArgs e)
  3. {
  4. SqlCommand getCar = new SqlCommand("select Car from myTable where carID = '"+ 3 +"' ", myConnection);
  5. myCar = getCar.ExecuteNoneQuery();
  6.  
  7. myCollection.Add(myCar.ToString());
  8. }

Share this Question
Share on Google+
2 Replies


P: 16
Instead of creating a new array each time, use
Expand|Select|Wrap|Line Numbers
  1. Array.Resize(ref array, newsize)
. Or you can use a collection:

Expand|Select|Wrap|Line Numbers
  1. List<string> myCollection = new List<string>();
  2. private void Combobox_SelectedIndexChanged(object sender, EventArgs e)
  3. {
  4. SqlCommand getCar = new SqlCommand("select Car from myTable where carID = '"+ 3 +"' ", myConnection);
  5. myCar = getCar.ExecuteNoneQuery();
  6.  
  7. myCollection.Add(myCar.ToString());
  8. }
Sep 21 '10 #2

JnrJnr
P: 88
Thanx Anton, Resizing the array works for me!
Bytes is awesome, Replies are more awesome
Sep 21 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.