C# dropbox of drives

user34537 picture user34537 · Mar 8, 2009 · Viewed 7k times · Source

I remember in vb6 there was a control that was similar to a dropbox/combobox that you can select the drive name. It raises an event which you can then set another control which enumerate files in listbox. (in drive.event you do files.path = drive.path to get this affect).

Is there anything like this in C#? a control that drops down a list of available drives and raises an event when it is changed?

Answer

Matt Hamilton picture Matt Hamilton · Mar 8, 2009

There's no built-in control to do that, but it's very easy to accomplish with a standard ComboBox. Drop one on your form, change its DropDownStyle to DropDownList to prevent editing, and in the Load event for the form, add this line:

comboBox1.DataSource = Environment.GetLogicalDrives();

Now you can handle the SelectedValueChanged event to take action when someone changes the selected drive.

After answering this question, I've found another (better?) way to do this. You can use the DriveInfo.GetDrives() method to enumerate the drives and bind the result to the ComboBox. That way you can limit which drives apppear. So you could start with this:

comboBox1.DataSource = System.IO.DriveInfo.GetDrives();
comboBox1.DisplayMember = "Name";

Now comboBox1.SelectedValue will be of type DriveInfo, so you'll get lots more info about the selected game. And if you only want to show network drives, you can do this now:

comboBox1.DataSource = System.IO.DriveInfo.GetDrives()
    .Where(d => d.DriveType == System.IO.DriveType.Network);
comboBox1.DisplayMember = "Name";

I think the DriveInfo method is a lot more flexible.