Monday 31 January 2011

Binding Images to GridView from a Folder in ASP.NET


In normal, there are many situations we required to show all/some the images stored in a folder to ASP.NET pages. In this post, we will look at some ways to show the images which are stored in a folder using GridView.

Before going to actual implementation, here are few scenarios which I am taking for example to implement in this post.

  1. The Images are stored in a folder inside of the application path. The system needs to get all the files and bind to the GridView.(Current Post)
  2. There is a text file stored in application which contains list of file name with path. The application required to fetch the file name from the text file and bind the imaged to the GridView.(Post)
  3. Same as Scenario 2, but addition to this the text file also contains some information about each image (Ex: Title of the Image, Description). So when showing images, the system also needs to show the information about the images.(Post)
  4. Same as Scenario 3, but the image file name, Title, and Description will be defined in XML file.(Post)
  5. Bind the images from folder or from a text file to GridView, But in Horizontal layout.(Post)

I am planning to cover each scenario in separate post. So this post will implement the first scenario – the images are stored in a folder inside of the application path.

This requirement again can be differentiated with the following ways –

  1. Normally get all the images from a folder and bind to the GridView.
    GridView Script
    <asp:GridView ID="grdImages" runat="server" BorderSt>le="None" GridLines="None"
        ShowHeader="false" AutoGenerateColumns="False" Width="240">
        <Columns>
            <asp:ImageField DataImageUrlField="FileName"></asp:ImageField>
        </Columns>
    </asp:GridView>
    C# Codebehind
    protected void Page_Load(object sender, EventArgs e)
    {
        string path = HttpContext.Current.Request.PhysicalApplicationPath + @"\Images\Temple";
        // string path = @"D:\Blog\Previous\ImageShow\Images\Temple"; // This statement also valid
    
        string[] files = System.IO.Directory.GetFiles(path, "*.jpg");
    
        IList<ImageFileInfo> imageFileList = new List<ImageFileInfo>();
        foreach (string strFileName in files)
        {
            // Change the Absolute path to relative path of File Name and add to the List
            imageFileList.Add(new ImageFileInfo { FileName = ResolveUrl(strFileName.Replace(Server.MapPath("/"), "~/")) });
        }
        grdImages.DataSource = imageFileList;
        grdImages.DataBind();
    }
    Define an Entity class for holding Image filename
    private class ImageFileInfo
    {
        public string FileName { get; set; }
    }
  2. Get only a specified extension (such as only .JPG files) and bind to the GridView.
    GridView Script will be same as above. C# code would be -
    protected void Page_Load(object sender, EventArgs e)
    {
        string path = HttpContext.Current.Request.PhysicalApplicationPath + @"\Images\Temple";
        // string path = @"D:\Blog\Previous\ImageShow\Images\Temple"; // This statement also valid
    
        string[] files = System.IO.Directory.GetFiles(path, "*.jpg"); // Here I am taking only .JPG ext files
    
        IList<ImageFileInfo> imageFileList = new List<ImageFileInfo>();
        foreach (string strFileName in files)
        {
            // Change the Absolute path to relative path of File Name and add to the List
            imageFileList.Add(new ImageFileInfo { FileName = ResolveUrl(strFileName.Replace(Server.MapPath("/"), "~/")) });
        }
        grdImages.DataSource = imageFileList;
        grdImages.DataBind();
    }
  3. Get the files with Multiple extensions (such as files with .JPG, .GIF and .PNG) and bind to the GridView.
    GridView Script will be same as above. C# code would be -
    protected void Page_Load(object sender, EventArgs e)
    {
        string path = HttpContext.Current.Request.PhysicalApplicationPath + @"\Images\Temple";
        // string path = @"D:\Blog\Previous\ImageShow\Images\Temple"; // This statement also valid
    
        string[] extensions = { "*.jpg", "*.png", "*.bmp" };
    
        List<string> files = new List<string>();
        foreach (string filter in extensions)
        {
            files.AddRange(System.IO.Directory.GetFiles(path, filter));
        }
    
        IList<ImageFileInfo> imageFileList = new List<ImageFileInfo>();
        foreach (string strFileName in files)
        {
            // Change the Absolute path to relative path of File Name and add to the List
            imageFileList.Add(new ImageFileInfo { FileName = ResolveUrl(strFileName.Replace(Server.MapPath("/"), "~/")) });
        }
        grdImages.DataSource = imageFileList;
        grdImages.DataBind();
    }
  4. While binding the Grid, show all the images with same Size (Width and Height).
    If you look at the above example output, the images will be shows in actual width and height. So if some images are big and small, it will be shown its actual size only. Below is the change (GridView) will show in predefined width and height.
    GridView Script
    <asp:GridView ID="grdImages" runat="server" BorderStyle="None" GridLines="None"
        ShowHeader="false" AutoGenerateColumns="False" Width="240">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("FileName") %>' Width="240" Height="160" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    C# code
    protected void Page_Load(object sender, EventArgs e)
    {
        string path = HttpContext.Current.Request.PhysicalApplicationPath + @"\Images\Temple";
        // string path = @"D:\Blog\ImageShow\Images\Temple"; // This statement also valid
    
        string[] files = System.IO.Directory.GetFiles(path, "*.jpg");
    
        IList<ImageFileInfo> imageFileList = new List<ImageFileInfo>();
        foreach (string strFileName in files)
        {
            // Change the Absolute path to relative path of File Name and add to the List
            imageFileList.Add(new ImageFileInfo { FileName = ResolveUrl(strFileName.Replace(Server.MapPath("/"), "~/")) });
        }
        grdImages.DataSource = imageFileList;
        grdImages.DataBind();
    }
  5. Here if the images are inside of the application path. For Ex: if the application path is C:\ExamApp\ImageShow, the images should be stored in the same path or inside of another folder from this path.
This code has been tested with IE 6.0/9.0, Firefox 3.6, Opera 11.01

Below is the output of the screen,
Bind Images from a Folder in ASP.NET

download the working example of the source code in C# here and in VB here


7 Responses to “Binding Images to GridView from a Folder in ASP.NET”

  • judel5 says:
    1 March 2012 at 20:32

    Hi,
    I like your post. I am working on a project where I am doing the exact thing and I have been looking for assistance for the longest. I will contact you with my specific question soon. Hope you can help, I will be very grateful.

  • Thirumalai M says:
    2 March 2012 at 10:15

    Hi judel5,

    You can contact me anytime. I will help you sure..

  • rani says:
    28 September 2012 at 16:08

    Its Really nice to see your article .It clarified my problem with image storage thank u

  • Anonymous says:
    11 November 2013 at 15:00

    GridView data binding in C#.NET

  • Unknown says:
    23 August 2017 at 11:26

    Its very useful to solve it..Thankyou so much..

  • Unknown says:
    23 August 2017 at 11:26

    Its very useful..Thanyou..

  • Unknown says:
    24 September 2017 at 14:08

    hi, i was trying with sub folders where images are present in different sub folders. but this doesn't work. can you provide any tweak please.

Post a Comment