简体   繁体   中英

Open local file from a web page using link in gridview c#

I need to open a some types of files like.jpg, word, .pdf when the user clicks on link in gridview. Right now i am using this code and its not opening up.

It is a web application and i have to open the file which is present in the local drive of user. I would be binding the path of file in NavigateUrl property of the hyperlink

<asp:hyperlink ID="HyplnkName" runat="server" NavigateUrl= '<%# ConfigurationManager.AppSettings["ImagesFilePath"]) %>' Target="_top" Text='<%# DataBinder.Eval(Container, "DataItem.FileName") %>' />

Here is what i used in my project

<asp:HyperLink ID="hlPdf" runat="server" NavigateUrl="~/PdfHandler.ashx" Target="_blank">Click to view PDF</asp:HyperLink>

This is ashx handler file

using System;
using System.Web;
using System.IO;

public class PdfHandler : IHttpHandler 
{

  public void ProcessRequest (HttpContext context) 
  {
    byte[] data = File.ReadAllBytes(@"Your Path");
    context.Response.ContentType = "application/pdf";
    context.Response.OutputStream.Write(data, 0, data.Length);
  }

  public bool IsReusable {
    get {
        return false;
    }
  }
}

use OnRowDataBound instead:

aspx page:

<asp:GridView ID="GridView1" runat="server" 
    onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
    <asp:HyperLink ID="HL" runat="server" Target ="_blank"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

code behind:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink hlink = (HyperLink)e.Row.FindControl("HL");
        string url = "~/Docs/" + e.Row.Cells[1].Text;
        hlink.NavigateUrl = url;
        hlink.Text = "Read";
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM