C # Возвращение к предыдущему изображению в виде списка и отображение его в Picturebox - PullRequest
0 голосов
/ 01 июня 2018

Я пытаюсь выбрать предыдущее изображение в виде списка и отобразить его в графическом окне справа.Я использую _imageIndex для отслеживания того, что в данный момент находится в графическом окне, и если оно меньше длины списка изображений, я выбираю изображение в виде списка и использую счетчик _imageIndex для доступа к изображению.

Нокак будто он вообще не получает индекс изображения.Он просто читает его в 0 и уменьшает его до отрицательного значения 1 и возвращает ошибку, когда я снова нажимаю btnPrevious.

System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '-1' is not valid for 'index'.
Parameter name: index'

Я знаю, что установил для _imageIndex значение 0 в событии mnuOpen_Click.Кроме этого я не знаю, как решить это.Для наглядности вот изображение GUI .Идеи пожалуйста?

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

    public Form1()
    {            
        InitializeComponent();
    }

    //Displays larger instance of selected image in picture box.
    private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //FOR i is less than the first image.
        for (int i = 0; i < listView1.SelectedItems.Count;i++)
        {                
            //GET filename from listview and store in index.
            _big_fileName = listView1.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);
        }
    }

    private void mnuOpen_Click(object sender, EventArgs e)
    {            
        loadImageList();
        _imageIndex = 0;
    }

    private void btnPrevious_Click(object sender, EventArgs e)
    {
        if (pictureBox1.Image != null)
        {                
            //IF Image is less than Image list size.
            if (_imageIndex < imageList1.Images.Count)
            {
                //SELECT  listview items with counter.
                listView1.Items[_imageIndex].Selected = true;
                //GO to previous entry.
                _imageIndex--;
            }
        }

        else
        {
            MessageBox.Show("No image.");
        }
    }

    //Cycle to next image in image list and display in Picturebox.
    private void btnNext_Click(object sender, EventArgs e)
    {
        if(pictureBox1.Image != null)
        {
            //IF Image is less than Image list size.
            if (_imageIndex < imageList1.Images.Count)
            {
                listView1.Items[_imageIndex].Selected = true;

                _imageIndex++;
            }
        }

        else
        {
            MessageBox.Show("No image.");
        }
    }

    private void loadImageList()
    {
        imageList1.Images.Clear();
        listView1.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;
            //Store filenames in string array.
            string[] arryFilePaths = new string[num_of_files];


            //FOREACH filename in the file.
            foreach (string single_file in oFD1.FileNames)
            {
                //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.
            listView1.LargeImageList = imageList1;


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

        catch (Exception ex)
        {
            MessageBox.Show("Error " + ex.Message);
        }
    }      
}

1 Ответ

0 голосов
/ 01 июня 2018

Прежде всего, вы нигде не устанавливаете _imageIndex, кроме как в btnPrevious_Click, где вы устанавливаете его на 0.

Вам необходимо установить его на выбранный индекс в методе SelectedIndexChanged, как это (обратите внимание напоследняя строка добавлена ​​в ваш предыдущий код):

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //FOR i is less than the first image.
        for (int i = 0; i < listView1.SelectedItems.Count; i++)
        {
            //GET filename from listview and store in index.
            _big_fileName = listView1.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 = listView1.SelectedIndices[0];
        }
    }

Далее, в btnPreviousClick вам нужно внести несколько изменений:

private void btnPrevious_Click(object sender, EventArgs e)
    {
        if (pictureBox1.Image != null)
        {
            //IF Image is less than Image list size.
            if (_imageIndex >= 0 && _imageIndex < imageList1.Images.Count)
            {
                //De-select current item
                listView1.Items[_imageIndex].Selected = false;
                //GO to previous entry.
                _imageIndex--;
                //Select new item
                if(_imageIndex>=0){
                   listView1.Items[_imageIndex].Selected = true;
                   listView1.Select();
                }
            }
        }
        else
        {
            MessageBox.Show("No image.");
        }
    }

Необходимо вызвать метод Select () в listView1.Самой большой проблемой было то, что вы не установили _imageIndex.

Надеюсь, это то, что вы искали:)

С наилучшими пожеланиями,

...