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
You misused the loop variable, I guess you need:
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
In the first iteration
"2"0So
item[i]resolved in"2"[0]which is"2"and it worked.In the second iteration
"1"1and 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.