Friday, May 31, 2013

How to download a file from Gridview using Link button in Asp.net

Introduction: In this post I try to explain how we can download the file from Gridview Data Control.
Gridview

Description:
I have created a table name DOWNLOAD_ASSIGNMENT. Here ID is primary key.
ID
int
CLASS
varchar(50)
ASSIGNMENT
varchar(MAX)

Add the Connectionstring in web.config file of website.
<configuration>
       <connectionStrings>
    <add name="con" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
       </connectionStrings>
       <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

Add a new webform to project. Drag and drop the Gridview Data Control from Toolbox.

  <asp:GridView ID="grdassignment" runat="server" AutoGenerateColumns="False"
           CssClass="Hover" RowStyle-CssClass="Hover"
            DataKeyNames="ASSIGNMENT" onrowcommand="grdassignment_RowCommand"
            >
            <Columns>
                <asp:TemplateField HeaderText="CLASS">
                    <ItemTemplate>
                        <asp:Label ID="lblname" runat="server" Text='<%# Eval("CLASS") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
              
                <asp:TemplateField HeaderText="DOWNLOAD ASSIGNMENT">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkdownlaod" runat="server" CommandArgument='<%# Eval("ASSIGNMENT") %>' CommandName="download"><b style="margin-left:50px;">Download</b></asp:LinkButton>
                    </ItemTemplate>
                                    </asp:TemplateField>
                                   
                           </Columns>
        </asp:GridView>

Now go to .aspx.cs page.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bindgridview();
        }
    }
    private void Bindgridview()
    {
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from DOWNLOAD_ASSIGNMENT", con);
            SqlDataReader dr = cmd.ExecuteReader();
            grdassignment.DataSource = dr;
            grdassignment.DataBind();

        }
        catch (Exception ex)
        {
        }
    }



    protected void grdassignment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        {
            try
            {
                if (e.CommandName == "download")
                {
                    string filename = e.CommandArgument.ToString();
                    if (filename != "")
                    {
                        string filepath = MapPath(filename);
                        byte[] bts = System.IO.File.ReadAllBytes(filepath);
                        Response.ClearHeaders();
                        Response.AddHeader("Content-Disposition", "attachment;   filename=" + filename);
                        Response.BinaryWrite(bts);
                        Response.Flush();
                        Response.End();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
    }

In VB (.aspx.vb)

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Bindgridview()
        End If
    End Sub
    Private Sub Bindgridview()
        Try
            Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
            con.Open()
            Dim cmd As New SqlCommand("select * from DOWNLOAD_ASSIGNMENT", con)
            Dim dr As SqlDataReader = cmd.ExecuteReader()
            grdassignment.DataSource = dr

            grdassignment.DataBind()
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub grdassignment_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
        Try
            If e.CommandName = "download" Then
                Dim filename As String = e.CommandArgument.ToString()
                If filename <> "" Then
                    Dim filepath As String = MapPath(filename)
                    Dim bts As Byte() = System.IO.File.ReadAllBytes(filepath)
                    Response.ClearHeaders()
                     Response.AddHeader("Content-Disposition", "attachment;   filename=" & filename)
                    Response.BinaryWrite(bts)
                    Response.Flush()

                    Response.[End]()
                End If
            End If
        Catch ex As Exception
        End Try
    End Sub


Now run the project and check the result.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment