In .aspx page :
——————
– Inside <asp:GridView -> 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='<%# Eval(“screenshot”) %>’ ??? – 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='<%# Eval(“screenshot”) %>’ ?
A: Again CommandArgument takes the ImageUrl which is obtained from the dataset.