Download File From GridView Using ASP.Net

Introduction

This article explains the following:

  • How to upload files using file upload control.
  • How to save a file in a folder and path to a database.
  • Displaying the list of files in a GridView that are already uploaded.
  • Downloading the files by clicking on the LinkButton.

Database

Use the following table and Stored Procedure to demonstrate this concept.

Table

Use the following script to create the preceding table.

  1. CREATE table FileDetails  
  2. (  
  3.    FileId int Primary Key Identity(1,1),  
  4.    FileName varchar(100),  
  5.    FileSize varchar(30),  
  6.    FileType varchar(30),  
  7.    FilePath varchar(200),  
  8.    CreatedOn Datetime  
  9. )  
  10.   
  11. Use the following script to Create the Stored procedures  
  12. --To get all File Details  
  13. CREATE procedure USP_Select_FileDetails  
  14. AS  
  15. Begin    
  16.  Select * from FileDetails  
  17. END  
  18.   
  19. --To Insert File Details  
  20. CREATE procedure USP_Insert_FileDetails  
  21.    @FileName varchar(100),  
  22.    @FileSize varchar(30),  
  23.    @FileType varchar(30),  
  24.    @FilePath varchar(200),  
  25.    @CreatedOn Datetime = Null  
  26. AS  
  27. Begin    
  28.  Insert FileDetails(FileName,FileSize,FileType,FilePath,CreatedOn)   
  29.  Values(@FileName,@FileSize,@FileType,@FilePath,GetDate())  
  30. END  

Creating the project

Now create the project using the following.

Go to Start, then All Programs and click Microsoft Visual Studio 2010
Go to File, then click New, Project..., Visual C# , Web. Then select ASP.NET Empty Web Application.

Provide the project a name and specify the location.

Empty Web Application


Web.Config

Create the connection string in the Web.Config file as in the following code snippet:

 

  1. <connectionStrings>  
  2.    <add name="conStr"  
  3.       connectionString="Password= 1234; User ID=sa; Database=DB_Jai; Data Source=."  
  4.       providerName="System.Data.SqlClient"/>  
  5. </connectionStrings>  

Next: Right-click on Solution Explorer and add a web form to your project.

Webform Design

Design you Webform (.aspx page) as in the following:

  1. <div align="center" style="width: 100%;">  
  2.     <fieldset style="width: 30%;">  
  3.         <legend>Download Files From GridView</legend>  
  4.         <table width="100%">  
  5.             <tr>  
  6.                 <td align="left">  
  7.                     <asp:FileUpload ID="FileUpload1" runat="server" />  
  8.                 </td>  
  9.                 <td align="left">  
  10.                     <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />  
  11.                 </td>  
  12.             </tr>  
  13.             <tr>  
  14.                 <td colspan="2" align="center">  
  15.                     <br />  
  16.                     <asp:Label ID="lblMsg" runat="server" ></asp:Label>  
  17.                 </td>  
  18.                 <tr>  
  19.                     <td colspan="2" align="center">  
  20.                         <br />  
  21.                         <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="False" Width="100%"  
  22.                             OnRowCommand="gvFiles_RowCommand">  
  23.                             <Columns>  
  24.                                 <asp:TemplateField HeaderText="Download Here">  
  25.                                     <ItemTemplate>  
  26.                                         <asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("FileName") %>'  
  27.                                             CommandName="Download" Text='<%# Eval("FileName") %>' />  
  28.                                     </ItemTemplate>  
  29.                                 </asp:TemplateField>  
  30.                                 <asp:BoundField DataField="FileSize" HeaderText="File Size" />  
  31.                                 <asp:BoundField DataField="FileType" HeaderText="File Type" />  
  32.                             </Columns>  
  33.                         </asp:GridView>  
  34.                     </td>  
  35.                 </tr>  
  36.         </table>  
  37.     </fieldset>  
  38. </div>  
CodeBehind

Add the following namespaces: 
  1. using System.Data;  
  2. using System.IO;  
  3. using System.Data.SqlClient;  
  4. using System.Configuration;  
  5. using System.Drawing;  
Invoke the ConnectionString from Web.Config as in the following:
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);  
User Defined Functions

#region User Defined Methods
  1. //Get file type by Extension  
  2. private string GetFileExtension(string fileExtension)  
  3. {  
  4.     switch (fileExtension.ToLower())  
  5.     {  
  6.         case ".docx":  
  7.         case ".doc":  
  8.             return "Microsoft Word Document";  
  9.         case ".xlsx":  
  10.         case ".xls":  
  11.             return "Microsoft Excel Document";  
  12.         case ".txt":  
  13.             return "Text Document";  
  14.         case ".jpg":  
  15.         case ".png":  
  16.             return "Image";  
  17.         default:  
  18.             return "Unknown";  
  19.     }  
  20. }  
  21.   
  22. //Save File in folder and File details and Path to database  
  23. private void UploadFile()  
  24. {  
  25.     string FileName = string.Empty;  
  26.     string FileSize = string.Empty;  
  27.     string extension = string.Empty;  
  28.     string FilePath = string.Empty;  
  29.   
  30.     if (FileUpload1.HasFile)  
  31.     {  
  32.         extension = Path.GetExtension(FileUpload1.FileName);  
  33.         FileName = FileUpload1.PostedFile.FileName;  
  34.         FileSize = FileName.Length.ToString() + " Bytes";  
  35.         //strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload1.FileName;  
  36.         FileUpload1.PostedFile.SaveAs(Server.MapPath(@"~/Application/FileUploads/" + FileName.Trim()));  
  37.         FilePath = @"~/Application/FileUploads/" + FileName.Trim().ToString();  
  38.     }  
  39.     else  
  40.     {  
  41.         lblMsg.Text = "Plase upload the file";  
  42.         lblMsg.ForeColor = Color.Red;  
  43.         return;  
  44.     }  
  45.   
  46.     SqlCommand cmd = new SqlCommand("USP_Insert_FileDetails", con);  
  47.     cmd.CommandType = System.Data.CommandType.StoredProcedure;  
  48.     cmd.Parameters.AddWithValue("@FileName", FileName);  
  49.     cmd.Parameters.AddWithValue("@FileSize", FileSize);  
  50.     cmd.Parameters.AddWithValue("@FileType", GetFileExtension(extension));  
  51.     cmd.Parameters.AddWithValue("@FilePath", FilePath);  
  52.     con.Open();  
  53.     int result = cmd.ExecuteNonQuery();  
  54.     if (result > 0)  
  55.     {  
  56.         lblMsg.Text = "File Uploaded Successfully ";  
  57.         lblMsg.ForeColor = Color.Green;  
  58.         BindGridView();  
  59.     }  
  60. }  
  61.   
  62. //Displaying the list of files in GridView that are already uploaded  
  63. private void BindGridView()  
  64. {  
  65.     SqlDataAdapter adp = new SqlDataAdapter("USP_Select_FileDetails", con);  
  66.     adp.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;  
  67.     if (con.State != ConnectionState.Open)  
  68.     {  
  69.         con.Open();  
  70.     }  
  71.     DataSet ds = new DataSet();  
  72.     adp.Fill(ds);  
  73.     gvFiles.DataSource = ds;  
  74.     gvFiles.DataBind();  
  75. }  
Page Event Handlers

#region Page Event Handlers.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     lblMsg.Text = string.Empty;  
  4.     if (!Page.IsPostBack)  
  5.     {  
  6.         BindGridView();  
  7.     }  
  8. }  
  9.   
  10. protected void btnUpload_Click(object sender, EventArgs e)  
  11. {  
  12.     UploadFile();  
  13. }  
  14.   
  15. protected void gvFiles_RowCommand(object sender, GridViewCommandEventArgs e)  
  16. {  
  17.     Response.Clear();  
  18.     Response.ContentType = "application/octet-stream";  
  19.     Response.AppendHeader("Content-Disposition""filename=" + e.CommandArgument);  
  20.     Response.TransmitFile(Server.MapPath("~/Application/FileUploads/") + e.CommandArgument);  
  21.     Response.End();  
  22. }  
#endregion

Output

Upload the file using file upload control and click on the Upload button. The uploaded file is displayed in the GridView. Next click on the link button to download the files.

GridView

I hope you enjoyed this article. Please provide your valuable suggestions and feedback. 


Similar Articles