Wednesday, 29 October 2014

Asp.net Display List of Files from Server Folder in Gridview

Asp.net Display List of Files from Server Folder in Gridview using C#

To display files from folder in Gridview we need to write the code like as shown below


 first create new web application and write the following code in aspx page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get files from folder & bind to gridview in c#.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGetFiles" Text="Get Files From Folder" runat="server" onclick="btnGetFiles_Click" />
<asp:GridView ID="gvDetails" CellPadding="5" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>

</html>

 
 Once you add namespaces write the following code in code behind
C# Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;

 // insert files in folder
protected void btnGetFiles_Click(object sender, EventArgs e)
{
BindGridview();
}
// Bind Data to Gridview
protected void BindGridview()
{
string[] filesPath = Directory.GetFiles(Server.MapPath("~/SampleFiles/"));
List<ListItem> files = new List<ListItem>();
foreach (string path in filesPath)
{
files.Add(new ListItem(Path.GetFileName(path)));
}
gvDetails.DataSource = files;
gvDetails.DataBind();
}