0

I am trying to insert a person's name into a specific position within my arraylist, i get an error when i run this:

public void InsertIntoArrayList(string actName, int posNum)
{
    snip
}

The user would enter the name into the name textbox then the position(index) at which to insert the string.. Any suggestions on an easier way to code this or a way i can change it?

The error i get is - that the index is out of range. i assume the conversion might be messed up?

Mirro A
  • 163
  • 2
  • 3
  • 14
  • 1
    show how you create ActorArrayList and the exact error message – ilansch Sep 25 '13 at 07:31
  • Have you checked that the posNum is actually a number that you can insert to? Like within size of the ArrayList? – Yao Bo Lu Sep 25 '13 at 07:32
  • System.Collections.ArrayList ActorArrayList = new System.Collections.ArrayList(); The array list is filled with 5 names from a text file, then the user is able to add new names to it via the form and it will display in a combo box. – Mirro A Sep 25 '13 at 07:45
  • Are you asking a second, unrelated question with your last edit? Then clarify if your original question was answered(you can do that with the accept-button left beside an answer). Then ask another question. – Tim Schmelter Sep 25 '13 at 08:15
  • yeah i had a second quick question, didnt know how to do it.. i just edited it in.. – Mirro A Sep 25 '13 at 08:39

2 Answers2

2

Indices are zero based. So the first item is at index 0 and the tenth item at index 9. ArrayList.Insert:

int posNum;
if(!int.TryParse(txtPosition.Text, out posNum))
{
    // show message
    return;
}
else if(posNum < 0 || posNum > ActorArrayList.Count)
{
    // show message
    return;
}
ActorArrayList.Insert(posNum, actName);

If you want to add the object at the end anyway, you just have to use Add:

ActorArrayList.Add(actName);

Note: you should use a strongly typed List<T> instead of a ArrayList, they are redundant meanwhile. c# When should I use List and when should I use arraylist?

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You could always use the .ToList on your array then the List insert function.

Iain Brown
  • 133
  • 3
  • 12