Hi indradeo,
Check this sample. now take its reference.
HTML
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="OnUpload" /><br /><br />
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Value" HeaderText="ID" />
<asp:BoundField DataField="Text" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="View" runat="server" OnClick="OnView" CommandArgument='<%# Eval("Text") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView><br /><br />
<asp:Image runat="server" id="imgView" Width="100px" Height="100px" />
Namespaces
C#
using System.Collections.Generic;
using System.IO;
VB.Net
Imports System.Collections.Generic
Imports System.IO
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
List<ListItem> files = new List<ListItem>();
int id = 1;
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem { Text = fileName, Value = Convert.ToString(id) });
id++;
}
this.gvImages.DataSource = files;
this.gvImages.DataBind();
}
}
protected void OnView(object sender, EventArgs e)
{
string fileName = (sender as LinkButton).CommandArgument;
this.imgView.ImageUrl = "~/Images/" + fileName;
}
protected void OnUpload(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
}
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("~/Images/"))
Dim files As List(Of ListItem) = New List(Of ListItem)()
Dim id As Integer = 1
For Each filePath As String In filePaths
Dim fileName As String = Path.GetFileName(filePath)
files.Add(New ListItem With {
.Text = fileName,
.Value = Convert.ToString(id)
})
id += 1
Next
Me.gvImages.DataSource = files
Me.gvImages.DataBind()
End If
End Sub
Protected Sub OnView(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = (TryCast(sender, LinkButton)).CommandArgument
Me.imgView.ImageUrl = "~/Images/" & fileName
End Sub
Protected Sub OnUpload(ByVal sender As Object, ByVal e As EventArgs)
If FileUpload1.HasFile Then
Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") & fileName)
Response.Redirect(Request.Url.AbsoluteUri)
End If
End Sub
Screenshot