How to Retrieve All Local Drives in the DataGridView Using C#

This tutorial that I’m going to teach you is about how to retrieve all local drives in the datagridview using C#. This is a very useful method when you want to display all computer drives in the datagridview to see what drives are offered on your personal computer. Follow the step by step guide in creating this simple program.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Add a DataGridView inside the Form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, create a method for getting all local drives.
  1.  
  2. private void getAllDrives()
  3. {
  4. dataGridView1.Rows.Clear();
  5. dataGridView1.Columns.Add("Name", "Name");
  6. dataGridView1.Columns.Add("Letter", "Letter");
  7. dataGridView1.Columns.Add("Type", "Type");
  8. foreach (DriveInfo drive in DriveInfo.GetDrives())
  9. {
  10. string driveName, driveType,driveletter;
  11. driveName = drive.Name;
  12. driveType = "";
  13. driveletter = drive.Name;
  14.  
  15. if(drive.IsReady && drive.VolumeLabel != "")
  16. {
  17. driveName = drive.VolumeLabel;
  18. }
  19. else
  20. {
  21. switch (drive.DriveType) {
  22. case DriveType.Fixed : driveName = "Local Disk"; break;
  23. case DriveType.CDRom : driveName = "CD-ROM"; break;
  24. case DriveType.Network : driveName = "Network Drive"; break;
  25. case DriveType.Removable : driveName = "Removable Disk"; break;
  26. }
  27.  
  28. }
  29. switch (drive.DriveType)
  30. {
  31. case DriveType.Fixed: driveName = "Local Disk"; break;
  32. case DriveType.CDRom: driveName = "CD-ROM"; break;
  33. case DriveType.Network: driveName = "Network Drive"; break;
  34. case DriveType.Removable: driveName = "Removable Disk"; break;
  35. }
  36.  
  37. dataGridView1.Rows.Add(driveName,driveletter,driveType);
  38. }
  39. }

Step 4

Execute the method that you have created in the first load of the form.
  1.  
  2. private void Form1_Load(object sender, EventArgs e)
  3. {
  4. getAllDrives();
  5. }
The complete source code is included. You can download it and run it on your computer. For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment