'When using a trackBar to move through images in pictureBox when getting to the last image in the array getting exception out of range. How to solve?
The exception is on the line
pictureBox1.Image = Image.FromFile(images[(int)value]);
It happens when I'm moving the trackBar to the right to the end and at the last one the exception is thrown.
The problem is that there is 35 images in the array and also the value is 35.
How can i solve it?
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
There is 35 images in the array and the value is 35 when the exception happens.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyImages
{
public partial class Editor : Form
{
private string[] images;
public Editor()
{
InitializeComponent();
//images =
images = GetImages();
macTrackBar2.Maximum = images.Length;
}
private void Editor_Load(object sender, EventArgs e)
{
}
public string[] GetImages()
{
string rootPath = Environment.ExpandEnvironmentVariables(@"d:\MyImages");
DirectoryInfo directory = new DirectoryInfo(rootPath).GetDirectories()
.OrderByDescending(d => d.CreationTimeUtc)
.First();
FileInfo[] files = directory.GetFiles("*.gif");
images = files.Select(f => f.FullName).ToArray();
Array.Sort(images, new MyComparer(true));
return images;
}
private class MyComparer : IComparer<string>
{
public static readonly MyComparer Descending = new MyComparer(false);
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public int Compare(string psz1, string psz2)
{
return (Reverse ? -1 : 1) * StrCmpLogicalW(psz1, psz2);
}
public MyComparer(bool reverse)
{
Reverse = reverse;
}
public bool Reverse { get; private set; }
}
private void macTrackBar2_ValueChanged(object sender, decimal value)
{
pictureBox1.Image = Image.FromFile(images[(int)value]);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
