Tuesday, June 26, 2012


Download file using GridView in Asp.Net

In some of the cases we want to give file listing with  download option.

Here I am explaining, How to download file using GridView in Asp.Net ?

For this task, I have created my Database table like this-

FileDetails(FileId,FileName,FilePath)

FileId -  Auto generated filed, to maintain primary key for file
FileName - Name of Uploaded file
FilePath - Complete file path for uploaded file


Here is code-

.aspx code-



    
    
   
       
           

                No Data Found.
           

       
       
           
               
                   
               
           
           
               
                   
               
           
           
               
                   
               
           
           
               
                   
               
           
       
   
   



In above code, I have taken 4 columns in GridView , but here FilePath is hidden, I am not showing FilePath.

I am passing FilePath value using  CommandArgument property,  this value will be used in server side code to download file. For button I have set CommandName="download" so that button click can be handled in RowCommand() event of GridView.


    
                   
           
                   
       



The output of this  .aspx will be -



Now .cs code-

 protected void grdFileDetails_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                //Code to download file
                if (e.CommandName == "download")
                {
                    string filepath = Convert.ToString(e.CommandArgument);

                    byte[] data = System.IO.File.ReadAllBytes(filepath);
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.AddHeader("Content-Type", "Application/octet-stream");
                    Response.AddHeader("Content-Length", data.Length.ToString());
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + filepath);
                    Response.BinaryWrite(data);
                    Response.End();
                }

            }

            catch (Exception)
            {
                 throw;
            }
        }


In above code, I have implemented GridVIew_RowCommand() event , here first I am checking commandName value using e.CommandName.

To get particular file path here I am using e.CommandArgument like this-
   string filepath = Convert.ToString(e.CommandArgument);

 After gettting Filepath I have used Response object to download file like this-
  
   Response.BinaryWrite(data);
  


Here data will contain binary data that will be downloaded as a file. 

Now if you will click on download button then related file will be downloaded.

No comments:

Post a Comment