【问题标题】:Scroll to top and bottom on listbox滚动到列表框的顶部和底部
【发布时间】:2013-01-25 06:22:48
【问题描述】:

我有一个名为 lstFilesListBox,它显示图像的文件名,然后在从列表框中选择时,通过鼠标或键盘。

然后图像将显示在 PictureBox pictureBox1 中,但是在列出最后一个条目后,我无法尝试使 ListBox 返回顶部,如果您在最后一个条目上选择了键盘上的向下箭头,并选择了顶部条目,当您在第一个条目上按向上箭头键时,我希望同样进入底部条目。

我已经尝试过,但无法让它在列表框中工作

我有三个联合列表框来显示系统驱动器、文件夹及其内容

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;

        }
      }
   }

【问题讨论】:

标签: c# listbox


【解决方案1】:

您可以通过处理ListBox KeyUp 事件来完成此操作。试试这个:

    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;
    }

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多