Open PDF in new window or tab on ASP.Net GridView ImageButton Click using C# and VB.Net

Hazel
 
on Oct 23, 2021 07:40 PM
503 Views

How to open pdf in new window

I have code to open file but i want it to open in new window.

protected void imgBtnEvidDownload_Click(object sender, ImageClickEventArgs e)
{
    string filePath = Server.MapPath("~/isoEvidence/" + (sender as ImageButton).CommandArgument);
    
    FileInfo file = new FileInfo(filePath);
 
    // Checking if file exists
    if (file.Exists)
    {
        // Clear the content of the response
        Response.ClearContent();
 
        // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
        Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);
 
        // Add the file size into the response header
        Response.AddHeader("Content-Length", file.Length.ToString());
 
        // Set the ContentType
        Response.ContentType = ReturnExtension(file.Extension.ToLower());
 
        // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
        Response.TransmitFile(file.FullName);
 
        // End the response
        Response.End();
    }
}
 
private string ReturnExtension(string fileExtension)
{
    switch (fileExtension)
    {
        case ".jpg":
            return "image/jpg";
        case ".jpeg":
            return "image/jpeg";
        default:
            return "application/pdf";
    }
}

please help. TQ.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 25, 2021 04:48 AM

Hi Hazel,

Check this example. Now please take its reference and correct your code.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Text" HeaderText="File Name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton AlternateText="Open" CommandArgument='<%# Eval("Value") %>'
                    runat="server" OnClick="OnOpen"></asp:ImageButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespaces

C#

using System.IO;
using System.Text;

VB.Net

Imports System.IO
Imports System.Text

Code

Default

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/Files/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), Path.GetFileName(filePath)));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
    }
}

protected void OnOpen(object sender, ImageClickEventArgs e)
{
    string fileName = (sender as ImageButton).CommandArgument;
    string url = "Download.aspx?FileName=" + fileName;
    StringBuilder sb = new StringBuilder();
    sb.Append("<script type = 'text/javascript'>");
    sb.Append("window.open('");
    sb.Append(url);
    sb.Append("');");
    sb.Append("</script>");
    ClientScript.RegisterStartupScript(this.GetType(), "script", sb.ToString());
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Files/"))
        Dim files As List(Of ListItem) = New List(Of ListItem)()
        For Each filePath As String In filePaths
            files.Add(New ListItem(Path.GetFileName(filePath), Path.GetFileName(filePath)))
        Next
        GridView1.DataSource = files
        GridView1.DataBind()
    End If
End Sub

Protected Sub OnOpen(ByVal sender As Object, ByVal e As ImageClickEventArgs)
    Dim fileName As String = TryCast(sender, ImageButton).CommandArgument
    Dim url As String = "Download.aspx?FileName=" & fileName
    Dim sb As StringBuilder = New StringBuilder()
    sb.Append("<script type = 'text/javascript'>")
    sb.Append("window.open('")
    sb.Append(url)
    sb.Append("');")
    sb.Append("</script>")
    ClientScript.RegisterStartupScript(Me.GetType(), "script", sb.ToString())
End Sub

Download

C#

protected void Page_Load(object sender, EventArgs e)
{
    string filePath = Server.MapPath("~/Files/" + Request.QueryString["FileName"]);
    System.IO.FileInfo file = new System.IO.FileInfo(filePath);
    if (file.Exists)
    {
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = ReturnExtension(file.Extension.ToLower());
        Response.TransmitFile(file.FullName);
        Response.End();
    }
}

private string ReturnExtension(string fileExtension)
{
    switch (fileExtension)
    {
        case ".jpg":
            return "image/jpg";
        case ".jpeg":
            return "image/jpeg";
        default:
            return "application/pdf";
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim filePath As String = Server.MapPath("~/Files/" & Request.QueryString("FileName"))
    Dim file As IO.FileInfo = New IO.FileInfo(filePath)
    If file.Exists Then
        Response.ClearContent()
        Response.AddHeader("Content-Disposition", "inline; filename=" & file.Name)
        Response.AddHeader("Content-Length", file.Length.ToString())
        Response.ContentType = ReturnExtension(file.Extension.ToLower())
        Response.TransmitFile(file.FullName)
        Response.End()
    End If
End Sub

Private Function ReturnExtension(ByVal fileExtension As String) As String
    Select Case fileExtension
        Case ".jpg"
            Return "image/jpg"
        Case ".jpeg"
            Return "image/jpeg"
        Case Else
            Return "application/pdf"
    End Select
End Function

Screenshot