csharp

Display list of files from Server folder in ASP.Net GridView Using C#

Click this link for :Download Code and Database
In this blog, We will learn Display list of files from Server folder in ASP.Net GridView Using C#.
In this article, I will explain with an example, Display list of files from Server folder in ASP.Net GridView Using C# using FileUpload control.

Step by step learn Display list of files from Server folder in ASP.Net GridView Using C#.
Next articleHow to Download Display list of Files from Griidview in ASP.Net C#
Step 1:Database

For this blog i have created a Database and Simple Table with the four column “ImageId”,”Image”,”ContentType” and “Data”.
[php]
Create Database FileUpload_Demo1
use FileUpload_Demo1

Create table tblFileUpload(
ImageId int primary key identity(1,1),
ContentType nvarchar(250),
Image varchar(50),
Data varbinary(Max)
)
[/php]
Step 2:Stored Procedure For Insert, Retrieve File
Create Stored procedure for Insert data into Database.
[php]
create proc sp_tblFileUpload_Insert
@ContentType nvarchar(250),
@Image varchar(50),
@Data varbinary(Max)
as
begin
insert into tblFileUpload(ContentType,Image,Data) values(@ContentType,@Image,@Data)
end
[/php]

Create Stored procedure for retrieve Data from the database.
[php]
create proc [dbo].[sp_tblFileUpload_Get]
as
begin
select * from tblFileUpload
end
[/php]

Step 3:Now Open Visual Studion and create the project as:
“Start” –> “All Programs”- “Microsoft Visual Studio 2012”.
“File” – “New Project” – “C#” – “Empty Project” (to avoid adding a master page).
Give the Project name such as “FileUpload_Demo” or another as you wish and specify the location.
Then right-click on Solution Explorer – “Add New Item” – “Default.aspx” page.
Step 4: Go back to your website in Solution Explorer and Add New Folder and Give name as – New Folder, then Uploads.
Add Upload Folder in Your Project

Step 5:Open Default.aspx page and write this code.
In “Default.aspx” page drag and drop one of an ASP.Net FileUpload control, and one Button and one Gridview control. The Button has been assigned a Click event handler.
FileUpload and Button used to upload and save the files to the database and an ASP.Net GridView control basically used to display the uploaded or stored files.
[php]
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:FileUpload ID="fuimage" runat="server"></asp:FileUpload>
</td>
<td></td>
</tr>
<tr>
<td>
<asp:Button ID="btnUploadImage" runat="server" Text="Upload"
OnClick="btnUploadImage_Click" /></td>
</tr>
<tr>
<td>
<asp:GridView ID="grdBindFiles" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="img" runat="server" Width="40px" Height="40px" ImageUrl='<%#Eval("Image","~/Uploads/{0}") %>’ />
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
[/php]

Step 4: Open web.config file and Establish a connection with database

Key Point:

  • In initial catalog write Database Name
  • In data source you can simply write (.) /your server name/(local)
  • Integrated security for Authentication

[php]
<connectionStrings>
<add name="DBCS" connectionString="data source=.;initial catalog=FileUpload_Demo1;integrated security=true"/>
</connectionStrings>
[/php]

Step 5:Open Default.aspx.cs file to write code for Display list of files from Server folder in ASP.Net GridView Using C#.
Default.aspx.cs
[php]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//Need to Import these namespace
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
namespace FileUpload_Demo
{
public partial class Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);

protected void Page_Load(object sender, EventArgs e)
{
GridBindFile();
}

/// <summary>
/// Uploading the files and then saving in to the SQL Server Database table
///The below event handler gets fired when the Upload Button is clicked,
///it simply saves the file as Binary data format in the SQL Server Database.
///The name of the file, the content type (MIME type) and the actual file as an array of bytes are
///inserted into the database table "tblFileUpload".
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

protected void btnUploadImage_Click(object sender, EventArgs e)
{
string FN = "";
FN = Path.GetFileName(fuimage.PostedFile.FileName);
string contentType = fuimage.PostedFile.ContentType;
Stream fs = fuimage.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] bytes = br.ReadBytes((Int32)fs.Length);

con.Open();
SqlCommand cmd = new SqlCommand("sp_tblFileUpload_Insert", con);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("@empid", btnUploadImage.Text == "Save" ? 0 : ViewState["Eid"]);

if (FN != "")
{
fuimage.SaveAs(Server.MapPath("Uploads" + "\\" + FN));

cmd.Parameters.AddWithValue("@Image", FN);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", bytes);
}

cmd.ExecuteNonQuery();
con.Close();
GridBindFile();
}

//Displaying the uploaded files from the Database Table in ASP.Net GridView Control

public void GridBindFile()
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_tblFileUpload_Get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
grdBindFiles.DataSource = ds;
grdBindFiles.DataBind();
}
}

}
}
[/php]
Screenshot describe the output.
Screenshot

Demo

Any Question and Suggestion related to this article Display list of files from Server folder in ASP.Net GridView Using C#.
Please comment me.

Leave a Reply

Your email address will not be published.