Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

File download from GridView rows in ASP.NET 4.0

0.00/5 (No votes)
2 May 2013 1  
There will be one Link button in the GridView row. On clicking the Link button, the Image displayed in that row gets downloaded.
In .aspx page:
  • Inside columns tag, add one template field like below:
<asp:TemplateField HeaderText="Screen Shot">
    <ItemTemplate>
         <asp:Image ID="screenShot" runat="server" ImageUrl='<%# Eval("screenshot") %>' CssClass="image" AlternateText="No Screenshots available"/>
         <asp:LinkButton ID="lnkDownload" runat="server" CommandArgument='<%# Eval("screenshot") %>' CommandName="cmd">Download</asp:LinkButton>
   </ItemTemplate>
</asp:TemplateField>
  • Add one OnRowCommand="GridView1_RowCommand" event inside
    <asp:GridView tag.
In .cs page:
  • Define the event "GridView1_RowCommand" as follows:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {
 
   if (e.CommandName == "cmd")
   {
      string filename = e.CommandArgument.ToString();
      if (filename != "")
      {
         string path = MapPath(filename);
         byte[] bts = System.IO.File.ReadAllBytes(path);
         Response.Clear();
         Response.ClearHeaders();
         Response.AddHeader("Content-Type", "Application/octet-stream");
         Response.AddHeader("Content-Length", bts.Length.ToString());
 
         Response.AddHeader("Content-Disposition", "attachment;   filename=" + filename);
 
         Response.BinaryWrite(bts);
 
         Response.Flush();
 
         Response.End();
      }
   } 
}

Important Points

  • Example is given for Image download, but you can download files of any type by just giving the path in "CommandArgument" attribute
  • Q: What is ImageUrl='' ???
  • A: It is written to specify/evaluate the path of image that we got from dataset(column name in dataset is "screenshot").
  • Q: What is CommandArgument='' ???
  • A: Again CommandArgument takes the ImageUrl which is obtained from the dataset.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here