Take the 2-minute tour ×

I have a multiple values in ListBox. When I am Selecting a Single Value my code is working fine.

But when I am Selecting Multiple Values it is giving me this Exception:-

Index was outside the bounds of the array.

My code is:

if (submitButton == "Enroll Trainee")
    if (Request.Form["NonEnroll"] != null)
        int i = 0;
        string[] selected = Request.Form["NonEnroll"].Split(',');
        if (selected != null)
            if (selected.Count() != 0)
                foreach (var item in selected)
                    enrollDetails.TraineeID = Convert.ToInt32(item[i].ToString());//Getting Exception here
                    enrollDetails.TrainerID = Convert.ToInt32(Session["user"].ToString());
                    enrollDetails.dt = DateTime.Now;

        return View();

During the First Iteration it is working fine and also save first iteration result in my database. But when it starts second iteration it give me the above exception

share|improve this question

closed as too localized by nemesv, Thor, codesparkle, jonsca, Frank van Puffelen Sep 8 '12 at 11:48


I guess you need: enrollDetails.TraineeID = Convert.ToInt32(item); –  nemesv Sep 8 '12 at 8:58
Thanks man...Life saver..!!! –  Rahul Sep 8 '12 at 9:06

1 Answer 1

up vote 1 down vote accepted

You misused the loop variable, I guess you need:

enrollDetails.TraineeID = Convert.ToInt32(item);

Let me explain why you original code item[i].ToString() didn't worked:

Lets assume you got the list "2,1,3" then with the string split you have created the array of strings : new [] { "2", "1", "3" }

Then in your loop

  1. In the first iteration

    • item was "2"
    • i was 0

    So item[i] resolved in "2"[0] which is "2" and it worked.

  2. In the second iteration

    • item was "1"
    • i was 1

    and your code resolved in "1"[1] which thrown an exception because "1" is only one character long so the Index was outside the bounds of the array.

share|improve this answer
I didn't get your One Character Long point. –  Rahul Sep 8 '12 at 9:23
strings are basically array of chars. So the string "test" can be expressed as the array of the 't','e','s','t' chars. In C# all the arrays are indexed from 0. So with the "1"[1] you want to get the second element form the char array which has only one char '1'. –  nemesv Sep 8 '12 at 9:24
Yeah got your point. If i'll write instead of item item[0] then I guess it will also works. –  Rahul Sep 8 '12 at 9:38
