How to upload, download and delete files from GridView in Asp.net?

upload, download and delete files from GridView  in Asp.net
Click on image to enlarge
Introduction: In previous articles i explained How to bind,upload,download,delete image files from the GridView  and Load more records dynamically in Gridview on button click and  How to display Serial/Row Number automatically in GridView and  How to bind gridview using SqlDataAdapter, DataTable and Stored procedure in Sql server  and How to bind gridview using SqlDataAdapter, SqlCommand, DataSet and Stored procedure in Asp.net 
 In this article I have explained the way of uploading the image/file in the folder and displaying the file in Gridview from that directory, download the file from GridView and also how to delete the image/ files displayed in the GridView control using asp.net in both the C# and Vb languages.

Implementation: Let's create an asp.net web page to understand:


HTML Source Code
  • In the design page (.aspx) place a FileUpload Control, a Button control and a GridView Control as:
  <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Submit" onclick="btnUpload_Click"  />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            EmptyDataText = "No files uploaded" CellPadding="4"
            EnableModelValidation="True" ForeColor="#333333" GridLines="None">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:BoundField DataField="Text" HeaderText="File Name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
  • Create folder “images” in the root directory of your website
Asp.Net C# to Bind, Upload,Download and Delete images/files from GridView
  • In the (.aspx.cs) file write the code as:
First of all Include following namespaces:

using System.Collections.Generic;
using System.IO;

Then write the code as:

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    protected void BindGrid()
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/images/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), filePath));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(Server.MapPath("~/images/") + FileUpload1.FileName);
            BindGrid();
        }
        else
        {
            Response.Write("Please select file to upload");
        }

    }
    protected void DownloadFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        Response.WriteFile(filePath);
        Response.End();
    }
    protected void DeleteFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        File.Delete(filePath);
        BindGrid();
    }

Asp.Net VB Code  to Bind, Upload,Download and Delete images/files from GridView
  • In the (.aspx.vb) file write the code as:
First Include following namespaces:

Imports System.Collections.Generic
Imports System.IO
  • Then write the code as:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            BindGrid()
        End If
    End Sub
    Protected Sub BindGrid()
        Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/images/"))
        Dim files As List(Of ListItem) = New List(Of ListItem)
        For Each filePath As String In filePaths
            files.Add(New ListItem(Path.GetFileName(filePath), filePath))
        Next
        GridView1.DataSource = files
        GridView1.DataBind()
    End Sub
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        If FileUpload1.HasFile Then
            FileUpload1.SaveAs(Server.MapPath("~/images/") + FileUpload1.FileName)
            BindGrid()
        Else
            Response.Write("Please select file to upload")
        End If
    End Sub
    Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
        Dim filePath As String = TryCast(sender, LinkButton).CommandArgument
        Response.ContentType = ContentType
        Response.AppendHeader("Content-Disposition", "attachment; filename=" & Path.GetFileName(filePath))
        Response.WriteFile(filePath)
        Response.[End]()
    End Sub
    Protected Sub DeleteFile(ByVal sender As Object, ByVal e As EventArgs)
        Dim filePath As String = TryCast(sender, LinkButton).CommandArgument
        File.Delete(filePath)
        BindGrid()
    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

11 comments

Click here for comments
Anonymous
admin
September 13, 2013 ×

ThankYou

Reply
avatar
Anonymous
admin
September 21, 2013 ×

thank u..its very nice..

Reply
avatar
September 21, 2013 ×

Your welcome..keep reading :)

Reply
avatar
October 22, 2013 ×

Thanks for appreciating my work...stay connected and keep reading for more useful updates like this..:)

Reply
avatar
Anonymous
admin
October 30, 2013 ×

How to do the same thing using Javascript. I don't want server side.

Reply
avatar
Unknown
admin
May 26, 2014 ×

thank you sir it's really helpful...

Reply
avatar
May 26, 2014 ×

Hi..thanks for your feedback..i am glad you found this article helpful..stay connected and keep reading..:)

Reply
avatar
Neha
admin
December 02, 2014 ×

this code is very helpful.

Reply
avatar
December 04, 2014 ×

Thanks neha for your valuable comments..

Reply
avatar
Anonymous
admin
January 06, 2016 ×

Can I the code to open the file

Reply
avatar
Unknown
admin
February 28, 2020 ×

sir how to upload delete and download files in a database,using gridview???

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..