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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JnrJnr
    New Member
    • Oct 2009
    • 88

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

    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.

    Code:
    string[] myArray;
    Code:
    int Index;
    private void Combobox_Select edIndexChanged( object sender, EventArgs e)
    {
    SqlCommand getCar = new SqlCommand("sel ect Car from myTable where carID = '"+ 3 +"' ", myConnection);[/CODE]
    [CODE]myCar = getCar.ExecuteN oneQuery();

    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
  • Anton Zinchenko
    New Member
    • Sep 2010
    • 16

    #2
    Instead of creating a new array each time, use
    Code:
    Array.Resize(ref array, newsize)
    . Or you can use a collection:

    Code:
    List<string> myCollection = new List<string>();
    private void Combobox_SelectedIndexChanged(object sender, EventArgs e)
    {
    SqlCommand getCar = new SqlCommand("select Car from myTable where carID = '"+ 3 +"' ", myConnection);
    myCar = getCar.ExecuteNoneQuery();
    
    myCollection.Add(myCar.ToString());
    }

    Comment

    • JnrJnr
      New Member
      • Oct 2009
      • 88

      #3
      Thanx Anton, Resizing the array works for me!
      Bytes is awesome, Replies are more awesome

      Comment

      Working...