Thursday, March 28, 2013

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) andFileName(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#
01protected void btnUpload_Click(object sender, EventArgs e)
02    {
03        if (FileUpload1.HasFile)
04        {
05            string name = Path.GetFileName(FileUpload1.PostedFile.FileName);
06            string location = Server.MapPath("~/Docs/" + name);
07            FileUpload1.SaveAs(location);
08 
09            //Create SQL Connection and Command to Save File name in DataBase
10 
11            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
12            SqlConnection sqlCon = new SqlConnection(connectionString);
13            string strInsert = "INSERT INTO Files(FileName) VALUES(@FileName)";
14            SqlCommand command = new SqlCommand(strInsert, sqlCon);
15            command.Parameters.AddWithValue("@FileName", name);
16            sqlCon.Open();
17            int result = command.ExecuteNonQuery();
18            sqlCon.Close();
19 
20            if (result > 0)
21                lblMessage.Text = "Upload Successful";
22        }
23        GridView1.DataBind();
24    }

VB.NET
01Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
02 If FileUpload1.HasFile Then
03  Dim name As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
04  Dim location As String = Server.MapPath("~/Docs/" & name)
05  FileUpload1.SaveAs(location)
06 
07  'Create SQL Connection and Command to Save File name in DataBase
08 
09  Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
10  Dim sqlCon As New SqlConnection(connectionString)
11  Dim strInsert As String = "INSERT INTO Files(FileName) VALUES(@FileName)"
12  Dim command As New SqlCommand(strInsert, sqlCon)
13  command.Parameters.AddWithValue("@FileName", name)
14  sqlCon.Open()
15  Dim result As Integer = command.ExecuteNonQuery()
16  sqlCon.Close()
17 
18  If result > 0 Then
19   lblMessage.Text = "Upload Successful"
20  End If
21 End If
22 GridView1.DataBind()
23End Sub

Write this code in RowCommand Event of GridView

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

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

0 comments:

Post a Comment