Sunday, 8 April 2012

Upload and download a file from GridView in Asp.net using with C# and Vb || Gridview with file Download link button in Asp.net using with C# and Vb


The following article is showing about file uploading and downloading with Gridview in Asp.net.
First Design the source code with fileupload control and Gridview  from Toolbox in Visual studio 2010.
Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</div>
<div>
<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server"AutoGenerateColumns="false" DataKeyNames="FilePath">
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download"OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
    </div>
    </form>
</body>
</html>

Write the following code in Upload button click event and download link button click event in code behind side:

Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=naresh;Initial Catalog=student;User ID=sa;Password=123");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridviewData();
        }
    }

    private void BindGridviewData()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from FilesTable", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        gvDetails.DataSource = ds;
        gvDetails.DataBind();
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
        fileUpload1.SaveAs(Server.MapPath("Files/" + filename));
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con);
        cmd.Parameters.AddWithValue("@Name", filename);
        cmd.Parameters.AddWithValue("@Path""Files/" + filename);
        cmd.ExecuteNonQuery();
        con.Close();
        BindGridviewData();
    }

    protected void lnkDownload_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        string filePath = gvDetails.DataKeys[gvrow.RowIndex].Value.ToString();
        Response.ContentType = "image/jpg";
        Response.AddHeader("Content-Disposition""attachment;filename=\"" + filePath +"\"");
        Response.TransmitFile(Server.MapPath(filePath));
        Response.End();
    }
}



The following is the same code in Vb.net

Default.aspx.vb :

Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Partial Public Class _Default
    Inherits System.Web.UI.Page
    Private con As New SqlConnection("Data Source=naresh;Initial Catalog=student;User ID=sa;Password=123")
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            BindGridviewData()
        End If
    End Sub

    Private Sub BindGridviewData()
        con.Open()
        Dim cmd As New SqlCommand("select * from FilesTable", con)
        Dim da As New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        da.Fill(ds)
        con.Close()
        gvDetails.DataSource = ds
        gvDetails.DataBind()
    End Sub

    Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
        Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
        fileUpload1.SaveAs(Server.MapPath("Files/" & filename))
        con.Open()
        Dim cmd As New SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con)
        cmd.Parameters.AddWithValue("@Name", filename)
        cmd.Parameters.AddWithValue("@Path", "Files/" & filename)
        cmd.ExecuteNonQuery()
        con.Close()
        BindGridviewData()
    End Sub

    Protected Sub lnkDownload_Click(sender As Object, e As EventArgs)
        Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
        Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
        Dim filePath As String = gvDetails.DataKeys(gvrow.RowIndex).Value.ToString()
        Response.ContentType = "image/jpg"
        Response.AddHeader("Content-Disposition", "attachment;filename=""" & filePath & """")
        Response.TransmitFile(Server.MapPath(filePath))
        Response.[End]()
    End Sub
End Class


Build your application and run it then you will get output like the following:



6 comments:

  1. if i want to open the file only for reading purpose then is it possible? in new window?

    ReplyDelete
    Replies
    1. Yes, it is possible. for that you have to take one more linkbutton in Gridview as View. write code to open file in new tab in View linkbutton click event.

      Delete
  2. please can u also make the code in VB.NET, cos i dont know c#, especially that link_download function. thanks

    ReplyDelete
    Replies
    1. Imports System.Collections.Generic
      Imports System.Linq
      Imports System.Web
      Imports System.Web.UI
      Imports System.Web.UI.WebControls
      Imports System.Data
      Imports System.Data.SqlClient
      Imports System.IO

      Partial Public Class _Default
      Inherits System.Web.UI.Page
      Private con As New SqlConnection("Data Source=naresh;Initial Catalog=student;User ID=sa;Password=123")
      Protected Sub Page_Load(sender As Object, e As EventArgs)
      If Not IsPostBack Then
      BindGridviewData()
      End If
      End Sub

      Private Sub BindGridviewData()
      con.Open()
      Dim cmd As New SqlCommand("select * from FilesTable", con)
      Dim da As New SqlDataAdapter(cmd)
      Dim ds As New DataSet()
      da.Fill(ds)
      con.Close()
      gvDetails.DataSource = ds
      gvDetails.DataBind()
      End Sub

      Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
      Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
      fileUpload1.SaveAs(Server.MapPath("Files/" & filename))
      con.Open()
      Dim cmd As New SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con)
      cmd.Parameters.AddWithValue("@Name", filename)
      cmd.Parameters.AddWithValue("@Path", "Files/" & filename)
      cmd.ExecuteNonQuery()
      con.Close()
      BindGridviewData()
      End Sub

      Protected Sub lnkDownload_Click(sender As Object, e As EventArgs)
      Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
      Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
      Dim filePath As String = gvDetails.DataKeys(gvrow.RowIndex).Value.ToString()
      Response.ContentType = "image/jpg"
      Response.AddHeader("Content-Disposition", "attachment;filename=""" & filePath & """")
      Response.TransmitFile(Server.MapPath(filePath))
      Response.[End]()
      End Sub
      End Class

      Delete
  3. Can you teach me how to delete the file?

    ReplyDelete
  4. Hi Naresh,

    After clicking the save button in SaveDilougeBox,i want to update the downloaded time to database table please provide me the solution ,if it is cancel click no update needed.. Thank u

    ReplyDelete