Download Files From GridView Link Button In Asp.Net C# VB.NET

This Example explains how to Download Files From GridView Link Button In Asp.Net Using C# VB.NET when files are saved or stored on server and their path or file name is saved in sql server database.

Download Files From GridView LinkButton Using C# VB.NET Asp.Net
I have placed one FileUpload control on the page to upload files on the server, and saving id and file name in database.

GridView on the page is used to display uploaded file and provide download link.

Create one table in sql database and add two columns ID (int identity) and FileName(Varchar).


HTML SOURCE OF PAGE
   1:  <asp:FileUpload ID="FileUpload1" runat="server"/>
   2:  <asp:Button ID="btnUpload" runat="server" 
   3:              onclick="btnUpload_Click" 
   4:              Text="Upload" />
   5:  <asp:Label ID="lblMessage" runat="server"></asp:Label>
   6:   
   7:  <asp:GridView ID="GridView1" runat="server" 
   8:                AutoGenerateColumns="False" 
   9:                DataSourceID="SqlDataSource1" 
  10:                onrowcommand="GridView1_RowCommand">
  11:  <Columns>
  12:  <asp:BoundField DataField="ID" HeaderText="ID" 
  13:                  SortExpression="ID" />
  14:  <asp:BoundField DataField="FileName" 
  15:                  HeaderText="FileName" 
  16:                  SortExpression="FileName" />
  17:   
  18:  <asp:ButtonField ButtonType="Link" Text="Download" 
  19:                   CommandName="Dwn" 
  20:                   HeaderText="Files" />
  21:  </Columns>
  22:  </asp:GridView>
  23:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  24:  ConnectionString=
  25:  "<%$ ConnectionStrings:ConnectionString %>" 
  26:  SelectCommand="SELECT [ID], [FileName] 
  27:                 FROM [Files]">
  28:  </asp:SqlDataSource>

Write below mentioned code in Click Event of upload button

C#
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string name = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string location = Server.MapPath("~/Docs/" + name);
            FileUpload1.SaveAs(location);

            //Create SQL Connection and Command to Save File name in DataBase

            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection sqlCon = new SqlConnection(connectionString);
            string strInsert = "INSERT INTO Files(FileName) VALUES(@FileName)";
            SqlCommand command = new SqlCommand(strInsert, sqlCon);
            command.Parameters.AddWithValue("@FileName", name);
            sqlCon.Open();
            int result = command.ExecuteNonQuery();
            sqlCon.Close();

            if (result > 0)
                lblMessage.Text = "Upload Successful";
        }
        GridView1.DataBind();
    }

VB.NET
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
 If FileUpload1.HasFile Then
  Dim name As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
  Dim location As String = Server.MapPath("~/Docs/" & name)
  FileUpload1.SaveAs(location)

  'Create SQL Connection and Command to Save File name in DataBase

  Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
  Dim sqlCon As New SqlConnection(connectionString)
  Dim strInsert As String = "INSERT INTO Files(FileName) VALUES(@FileName)"
  Dim command As New SqlCommand(strInsert, sqlCon)
  command.Parameters.AddWithValue("@FileName", name)
  sqlCon.Open()
  Dim result As Integer = command.ExecuteNonQuery()
  sqlCon.Close()

  If result > 0 Then
   lblMessage.Text = "Upload Successful"
  End If
 End If
 GridView1.DataBind()
End Sub

Write this code in RowCommand Event of GridView

C#
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Dwn")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            string fName = row.Cells[1].Text;
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fName);
            Response.TransmitFile(Server.MapPath("~/Docs/" + fName));
            Response.End();
        }
    }

VB.NET
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
 If e.CommandName = "Dwn" Then
  Dim index As Integer = Convert.ToInt32(e.CommandArgument)
  Dim row As GridViewRow = GridView1.Rows(index)
  Dim fName As String = row.Cells(1).Text
  Response.ContentType = "application/octet-stream"
  Response.AddHeader("Content-Disposition", "attachment;filename=" & fName)
  Response.TransmitFile(Server.MapPath("~/Docs/" & fName))
  Response.[End]()
 End If
End Sub

Build and run the application


Download Sample Code


If you like this post than join us or share

9 comments:

Anonymous said...

Hello there, i have tried the code below ; it works but not as i expected. The fact is that when uploading , it insert the entry to the database twice for same file. Is there anything that can be done to correct this?


amiT jaiN said...

@Above: did you tried the source code i provided ?


Marcus said...

very nice!


Anonymous said...

Thanks, guys for wonderful site..

:)


Anonymous said...

it is really help me I just modified the code as i need but I really inspired by the code without the code I never find the way to develop a bunch of code as I need
the foundation ob the bunch of code on your code.


Anonymous said...

hi dear ......
i try this code but i can't do
i have three mistakes...........
first is in filelocation
second in if(e.command name="download")
third in (e.commandarguments)


Anonymous said...

very nice!

thank you amiT jaiN

I make you site my bookmark, now


Anonymous said...

download not working with me


Anonymous said...

hii, the code works properly but the only problem is when uploading , it insert the entry to the database twice for same file.


Find More Articles