-2

I am new to programming.. and I was not able to find the solution for the string[] Index was outside the bounds of the array solutions..- Can anyone explain, what in the below code is wrong. What would be the right way of declaring an array and limiting it dynamically?. Will it be fine to do so? -
I want to get the values of the array in the FOR loop - like TOkenlist[]={1,2,3} but I am trying to do in FOR LOOP

Tokenlist[0] = "1";
Tokenlist[1] = "2";
Tokenlist[2] = "3";

   //MY CODE FOLLOWS

    string[]  Tokenlist;
    string[] MassageTokenList;
    if (!(Convert.ToInt16(val_PhysioNumber.Text) == 0))
    {
        for (i=1; i <= Convert.ToInt16(val_PhysioNumber.Text); i++)
        {
            Tokenlist = new string[i];

            SqlCommand cmd = new SqlCommand("ClinicalInvoicing", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@name", txt_NameClinical.Text);
            cmd.Parameters.AddWithValue("@natID", txt_NatIDClinical.Text);
            cmd.Parameters.AddWithValue("@memberType", MemType);
            cmd.Parameters.AddWithValue("@serviceType", 1);

            string Token = cmd.ExecuteScalar().ToString();
            if (Token != "")
            {
                Tokenlist[i] = Token;
            }

        }
    }    

any help will be highly appreciated

  • When you are looking for help with an exception YOU SHOULD INCLUDE THE EXCEPTION IN THE QUESTION!!!!!! – John3136 Oct 23 '14 at 06:05
  • You have 2 Problems in your code that I can see: 1. Tokenlist[i] If you create an array with for example new String[i] that means that you have i elements inside of it BUT the indexes go form 0 to (i-1). Thus Tokenlist[i] throws an exception with out of bounds. 2. You are doing Tokenlist = new String[i] every iteration of the foreach which means you are RECREATING the whole array anew every iteration of the foreach loop. I don't think that this is what you have intended to do. If you really want a growing list of tokens without having to do much additional coding you should consider – Thomas Oct 23 '14 at 06:08
  • using List and declare it outside of the foreach and then use tokenlist.Add to add the tokens (doesnt get easier otherwise) – Thomas Oct 23 '14 at 06:09
  • @John3136 who told you that I was looking for an exception. – Syed Sohail Ahmed Oct 23 '14 at 06:39
  • @sriram Sakthivel - My Question is about my own code. - It is no way similar to any other question. – Syed Sohail Ahmed Oct 23 '14 at 06:47
  • @SyedSohailAhmed You should be able to understand what is `IndexOutOfRangeException` in linked quested and also how to fix it. – Sriram Sakthivel Oct 23 '14 at 08:04

1 Answers1

0

Don't use an array, use a List instead to dinamically allocate objects. Also, I think your I var should start in 0 instead of 1

Oscar
  • 13,594
  • 8
  • 47
  • 75