Hi Indradeo,
Set the GridView DataKeyNames property.
On Download button click get the value from DataKeys using the selected row index.
Please refer below sample.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="Value">
<Columns>
<asp:BoundField DataField="Text" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" runat="server" OnClick="DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
C#
using System.IO;
VB.Net
Imports System.IO
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
protected void DownloadFile(object sender, EventArgs e)
{
int index = ((sender as LinkButton).NamingContainer as GridViewRow).RowIndex;
string filePath = GridView1.DataKeys[index].Values[0].ToString();
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Uploads/"))
Dim files As List(Of ListItem) = New List(Of ListItem)()
For Each filePath As String In filePaths
files.Add(New ListItem(Path.GetFileName(filePath), filePath))
Next
GridView1.DataSource = files
GridView1.DataBind()
End If
End Sub
Protected Sub DownloadFile(ByVal sender As Object, ByVal e As EventArgs)
Dim index As Integer = TryCast((TryCast(sender, LinkButton)).NamingContainer, GridViewRow).RowIndex
Dim filePath As String = GridView1.DataKeys(index).Values(0).ToString()
Response.ContentType = ContentType
Response.AppendHeader("Content-Disposition", "attachment; filename=" & Path.GetFileName(filePath))
Response.WriteFile(filePath)
Response.End()
End Sub
Screenshot