1
votes

I have ListBox named lstFiles that display file names of images, then when selected from the listbox, from either mouse or keyboard.

The image will then be shown within a PictureBox pictureBox1, but I am having trouble trying to make the ListBox go back to the top after the last entry has been listed, If you selected the down arrow on the keyboard on the last entry, and have the top entry selected, I want the same going to the bottom entry when you hit the up arrow key on the first entry.

I have tried and can't get it to work within the listbox

I have three joint listboxes to display the system drive, folders and its content

private void lstDrive_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            lstFolders.Items.Clear();
        try
        {
            DriveInfo drive = (DriveInfo)lstDrive.SelectedItem;

            foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
                lstFolders.Items.Add(dirInfo);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
    {
        lstFiles.Items.Clear();

        DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;

        foreach (FileInfo fi in dir.GetFiles())
            lstFiles.Items.Add(fi);
    }

    private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
    {
        pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);

        //I have tried this, but it makes the selected cursor go straight to the bottom file//
        lstFiles.SelectedIndex = lstFiles.Items.Count - 1;

        }
      }
   }
1

1 Answers

2
votes

You could accomplish this by handling the ListBox KeyUp event. Try this :

    private int lastIndex = 0;

    private void listBox1_KeyUp(object sender, KeyEventArgs e)
    {

        if (listBox1.SelectedIndex == lastIndex)
        {
            if (e.KeyCode == Keys.Up)
            {
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
            }

            if (e.KeyCode == Keys.Down)
            {
                listBox1.SelectedIndex = 0;
            }                

        }

        lastIndex = listBox1.SelectedIndex;
    }