using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Windows.Forms; using System.IO; using System.Collections; namespace WindowsApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnConnection_Click(object sender, EventArgs e) { //Open a file dialog FolderBrowserDialog dialog = new FolderBrowserDialog(); string filePath = string.Empty; //Set the target folder path if (dialog.ShowDialog()== System.Windows.Forms.DialogResult.OK) { filePath = dialog.SelectedPath; } //Add a column of buttons to the current data grid view DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn(); buttonColumn.HeaderText = "Buttons"; //Register an event of click so that it raises when the user clicks a cell fichierGrid.CellClick += new DataGridViewCellEventHandler(fichierGrid_CellClick); //Add the buttons column to the grid fichierGrid.Columns.Add(buttonColumn); //Set the data source of the grid fichierGrid.DataSource = loadFiles(filePath); } void fichierGrid_CellClick(object sender, DataGridViewCellEventArgs e) { DataGridView grid = (DataGridView)sender; //the click will concern the first column if (e.ColumnIndex==0) { //Catch the row index of the clicked button int index = e.RowIndex; //Get the corresponding file path string path = grid[4, index].Value.ToString(); //Start the process as we have the path now System.Diagnostics.Process.Start(path); } } /// <summary> /// This method loads files /// </summary> /// <param name="folderPath">The folder path</param> /// <returns></returns> public List<File> loadFiles(string folderPath) { DirectoryInfo folder = new DirectoryInfo(folderPath); var requete = from element in folder.GetFiles() select new File { Name = element.Name, Folder = element.DirectoryName, Extension = element.Extension, Path = element.FullName }; return requete.ToList(); } } /// <summary> /// This class represent the files those are displyed in the grid view /// </summary> public class File { public string Name { get; set; } public string Folder { get; set; } public string Extension { get; set; } public string Path { get; set; } } }
Wednesday, May 25, 2011
Display files of a given folder within a DataGridView
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment