Add a directory of files to a datagrid

Post Content



For greater control, you can add the file data to a dataset, then bind the dataset to the datagrid.

Bind directory to Data Grid[-][--][++]

<codebox vbscript 250><%Dim archivePath as String = "C:\Test\"If Directory.Exists(archivePath) Then dirInfo = New DirectoryInfo(archivePath) Dim ds As New DataSet grdFiles.DataSource = dirInfo.GetFiles("*.*") grdFiles.DataBind()End IflblFileCount.Text = "Showing " & grdFiles.Items.Count & " of " & dirInfo.GetFileSystemInfos("*.*").Length " Files"%></codebox>

Changing Displayed Columns[-][--][++]

With just a default datagrid (AutoGenerateColumns=true) you will get a lot of usefull \columns, like Name, Path, Size in bytes, Creation/Modify time...To narrow down the columns you want, goto Property Builder on the dg, select columns.Bound ColumnTo simply display data, without events, select Bound Column, Give Header Text, \Data Field: would be name of the default dg from dirInfo (Name, CreationTime, Extension, Length...)Button ColumnAn example of making the Name of the file a LinkButton
Header Text File Name
Text Name
Text Field Name
Command Name download
Button Type LinkButton
Note, in this example, my datagrid has 2 columns, Name and Length, so the ItemDataBound functions converts the size to KB<codebox vbscript><%Private Sub grdFiles_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles grdFiles.ItemDataBound Select Case e.Item.ItemType Case ListItemType.AlternatingItem, ListItemType.Item 'Convert the size from bytes to kb e.Item.Cells(1).Text = Round(e.Item.Cells(1).Text / 1024, 1) End SelectEnd SubPrivate Sub grdFiles_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles grdFiles.ItemCommand Select Case e.Item.ItemType Case ListItemType.AlternatingItem, ListItemType.Item If e.CommandName = "download" Then Dim button As LinkButton = e.CommandSource Dim filePath As String = System.Configuration.ConfigurationSettings.AppSettings("ExecutiveAnalysisArchivesFolder") & Me.DLR_ID & "\" Dim fileName As String = button.Text Me.StreamFile(filePath, fileName) End If End SelectEnd Sub%></codebox>