Click here to Skip to main content
15,884,885 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
IndexOutOfBoundsException "Index was outside the bounds of the array."

This occurs when I try to append another item to the listview. It seems that when we add a new item, the array’s size gets reset to whatever we appended to it. So the size of the counter then becomes bigger than the array. Please tell me what I've done wrong! The error is on this line
C#
temp[_counter] = single_file;
in method
C#
loadImageList()

Here is my code.

C#
    public partial class Form1 : Form
    {
        string _big_fileName;
        int _counter = 0;
        int _imageIndex;

        #region Initializers
        public Form1()
        {            
            InitializeComponent();
        }

        //Displays larger instance of selected image in picture box.
        private void lstImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            //FOR i is less than the first image.
            for (int i = 0; i < lstImages.SelectedItems.Count; i++)
            {
                //GET filename from listview and store in index.
                _big_fileName = lstImages.SelectedItems[i].Text;
                //Create larger instance of image.
                pictureBox1.Image = Image.FromFile(_big_fileName);
                //Fill panel to the width and height of picture box.
                panel1.AutoScrollMinSize = new Size(pictureBox1.Image.Width, pictureBox1.Image.Height);
                _imageIndex = lstImages.SelectedIndices[0];
                loadImageMetaData();
            }
        }
		
        private void mnuOpen_Click(object sender, EventArgs e)
        {            
            loadImageList();
            _imageIndex = 0;
        }
		
        private void loadImageList()
        {
            imageList1.Images.Clear();
            lstImages.Clear();

            oFD1.InitialDirectory = "C:\\";
            oFD1.Title = "Open an Image File";
            oFD1.Filter = "JPEGS|*.jpg|GIFS|*.gif|PNGS|*.png|BMPS|*.bmp";

            //Open Dialog Box.
            var oldResults = oFD1.ShowDialog();

            if (oldResults == DialogResult.Cancel)
            {
                return;
            }

            try
            {
                //GET amount of filenames.
                int num_of_files = oFD1.FileNames.Length;
                //Temp array i created to solve the error.
                string[] temp = new string[num_of_files];
                //Store filenames in string array.
                string[] arryFilePaths = new string[num_of_files];


                //FOREACH filename in the file.
                foreach (string single_file in oFD1.FileNames)
                {
                    //IF there are more images I want to display.
                    if (_counter >= oFD1.FileNames.Length)
                    {
                        //Append and render those images to the end of the image list.
                        temp[_counter] = single_file;
                        imageList1.Images.Add(Image.FromFile(single_file));
                        _counter++;
                        break;
                    }
                    //ACCESS array using _counter to find file.
                    arryFilePaths[_counter] = single_file;
                        //CREATE image in memory and add image to image list.
                        imageList1.Images.Add(Image.FromFile(single_file));
                        _counter++;
                    
                    
                }
                //BIND image list to listview.
                lstImages.LargeImageList = imageList1;


                for (int i = 0; i < _counter; i++)
                {                    
                    //DISPLAY filename and image from image index param. 
                    lstImages.Items.Add(arryFilePaths[i], i);
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine("Error " + ex.Message);                
            }                      
        }        

        private void lstImages_DoubleClick(object sender, EventArgs e)
        {
            lstImages = abb.abbListview.Update(lstImages, "Form Header", lstImages.SelectedIndices[0]);
        }
    }
}


What I have tried:

Step 1

I tried changing this line
string[] arryFilePaths = new string[num_of_files];
to
string[] arryFilePaths = new string[num_of_files + _counter];

I was coding hopelessly at random here, this just overrides whatever is in the array and disposes of the previous items.

Step 2
I used this. It should be in my
C#
lstImages_DoubleClick
event.
Update Listview Items[^]

Step 3

Wrote pseudo code.
=====================
START
GET Counter
GET ArryTotalFiles.
DECLARE newArry.

IF (ArryTotalFiles isn't empty).
STORE inside tempArray ArrayTotalFiles and Count.
END IF
ELSE IF (tempArry isn't empty)
CLEAN ArrTotalFiles.
STORE in StringFileArray the ArryTotalFiles and Count.
END IF ELSE
END.
=====================
Yeah I know it looks nothing like what I wrote in my code. :(
Posted
Updated 27-Jun-18 18:42pm

1 solution

The simplest solution is not to use an array: use a List instead:
List<string> temp = new List<string>);
List<string> arryFilePaths = new List<string>);
You can then do this:
C#
   temp.Add(single_file);
...
arryFilePaths.Add(single_file);
And teh system will handle it all for you behind the scenes.

By the way, The ListView.Items collection also has an AddRange method, so this code:
C#
for (int i = 0; i < _counter; i++)
                {                    
                    //DISPLAY filename and image from image index param. 
                    lstImages.Items.Add(arryFilePaths[i], i);
                }
Can be done in a single statement:
C#
lstImages.Items.AddRange(arryFilePaths);
 
Share this answer
 
Comments
Jordan Nash 28-Jun-18 4:09am    
Hello,
Unfortunately I am having trouble compiling your code. Could you please show it in full with the loops and if statements if appropriate to this situation. Lastly, sorry but your use of the AddRange method doesn't appear to be working as it doesn't accept a string list.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900