When Selecting Multiple Values in Listbox getting exception Index was outside the bounds of the array in Linq to Entity

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;
                    db.EnrollTrainee.Add(enrollDetails);
                    db.SaveChanges();
                    i++;
                }

            }
        }
        populatelistbox();
        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

Answers


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.


Need Your Help

SWI-Prolog and constraints, library CLP(FD)

prolog constraints clpfd clpq

I'm playing around with constraints in (swi) prolog using the clpfd library.

Soap does not cast response fields to into typed objects

soap xsd wsdl

I am a SOAP newb assigned to resurrecting an old soap interface. I've ported the soap service onto a new tomcat at a new path (and left the client unchanged). I send the request:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.