Add a download Hyperlink in gridview in visual stu

2019-09-02 01:15发布

问题:

My problem is simple, I would like to make the last column of my gridview to be a download link to a file in local on my computer.

I have my datatable with 3 columns :

User_id, request_id, FilePath

FilePath is the path (string) to the file on my computer, what I've been trying is : In my gridview on the webpage display the 2 first columns (User_id and request_id). On the 3rd column I added a hyperlink field and tried to link it (with the property DataNavigateUrlField) to the content of the column FilePath.

I've ended up with dead links on which i can't even click, they just change color on mouseover.

Any one have a clue about that ? Thanks a lot

回答1:

A possible solution could be to use a TemplateField for your Hyperlink column:

<asp:GridView AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <a href='<%# DataBinder.Eval(Container.DataItem, "FilePath") %>'>
                    <%# DataBinder.Eval(Container.DataItem, "FilePath")%>
                </a>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

will create the desired output:

<tr>
    <td>
        <a href='c:/directory/file.xxx'>c:/directory/file.xxx</a>
    </td>
</tr>

It seems that a HyperLinkField does not accept a file path for its DataNavigateUrlFieldsproperty.


I tried to outsmart it by setting the DataNavigateUrlFormatString property:

<asp:HyperLinkField DataNavigateUrlFormatString="file:///{0}" DataNavigateUrlFields="FilePath" DataTextField="FilePath" />

but the issue remains and will only produce

<tr>
    <td>
        <a>c:/directory/file.xxx</a>
    </td>
</tr>


回答2:

try to use this

WebClient.DownloadFile(Uri,String)

And read this how to get needed event hyperlink