65.9K
CodeProject 正在变化。 阅读更多。
Home

文件夹、驱动器、目录浏览器

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.58/5 (35投票s)

2004年9月14日

CPOL

2分钟阅读

viewsIcon

124177

downloadIcon

3229

文件夹、驱动器、目录浏览器应用程序。

免责声明

此源代码由个人编写和维护,而非公司。它被免费提供给 Microsoft .NET 用户社区,期望用户采取任何必要措施使代码根据他们的需求运行。这包括调试和增强。源代码按“原样”提供,不保证其质量,也不存在程序员将发布任何更新的明示或暗示协议。程序员将自行决定发布更新并提供任何支持。

引言

本文主要面向 .NET WinForms 编程初学者。最近,我听说很多人对开发文件夹和文件对话框有疑问。实际上,它很简单。本文旨在提供 VB.NET 和 C# 中的一个简单示例,展示创建自定义驱动器列表框、目录列表框和文件列表框是多么容易。此程序使用 Visual Studio .NET 的最终版本开发。

将“DriveListBox”、“DirListBox”和“FileListBox”添加到 VS.NET 工具箱

选择“工具”菜单,然后选择“添加/删除工具箱项”。然后屏幕上将出现“自定义工具箱”。选择“.NET Framework 组件”选项卡,然后选中“DriveListBox”、“DirListBox”和“FileListBox”复选框,然后单击“确定”。现在,您可以将“DriveListBox”、“DirListBox”和“FileListBox”拖放到 Windows 窗体中。

driveListBox_SelectedIndex 方法

当用户从 DriveListBox 下拉列表中选择驱动器时,此方法会更新 DirListBox 的路径,使其与 DriveListBox 一致。如果驱动器不可用或丢失,或者存在其他问题,则会在屏幕上显示带有错误警报的消息,并恢复 DriveListBox 的原始选择。

private void driveListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    try
    {
        this.dirListBox1.Path = this.driveListBox1.Drive;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, 
                                            MessageBoxIcon.Error);
    }
}

dirListBox1_SelectedIndexChanged

当用户双击文件夹,或者由于驱动器更改而更新了 DirListBox 时,此方法会更新 FileListBoxPath,使其与 DirListBox 一致。如果目录不可用或丢失,或者存在其他问题,则会在屏幕上显示带有错误警报的消息。

private void dirListBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    try
    {
        this.fileListBox1.Path = this.dirListBox1.Path;
        this.lblFolder.Text = 
            dirListBox1.Path.Substring(dirListBox1.Path.LastIndexOf("\\")+1);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, 
                                            MessageBoxIcon.Error); 
    }
}

要退出应用程序,请使用以下代码

private void Exit_Click(object sender, System.EventArgs e)
{
    this.Dispose();
}

如需更多帮助和疑问,请发邮件至:vivekthangaswamy@rediffmail.com

© . All rights reserved.