Images in gridview control - c# example

asp.net image in gridview
In asp.net we need to show images in gridview. To show image in gridview we have to use TemplateColumn in gridview and Image web control inside it. asp.net 2.0 have ImageField that we can use to view image in gridview.

Sample code to show image in gridview [asp.net c#]

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" Runat="server" AutoGenerateColumns="False" 
  BorderWidth="1px" CellPadding="3" BorderStyle="None" 
  Font-Names="Arial">
    <FooterStyle></FooterStyle>
    <PagerStyle HorizontalAlign="Left"></PagerStyle>
    <HeaderStyle Font-Bold="True"></HeaderStyle>
    <Columns>
        <asp:BoundField HeaderText="Image No." DataField="ImageID">
            <ItemStyle HorizontalAlign="Center" 
              VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
        <asp:ImageField DataImageUrlField="ImagePath"></asp:ImageField>
    </Columns>
   </asp:GridView>
    </div>
    </form>
</body>
</html>

Below is C# code to show image in gridview

using System;
using System.Data;

namespace aspnetcontrol
{
    public partial class GridviewImages : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) 
        {
            GridView1.DataSource = BindImageData();
            GridView1.DataBind();
        }

       public DataTable BindImageData()     
        {
           
            DataTable dt = new DataTable();
           
            dt.Columns.Add(new DataColumn("ImageID", typeof(int)));
            dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));
            // Create the four records
            DataRow dr = dt.NewRow();
            dr["ImageID"] = 1;
            dr["ImagePath"] = ResolveUrl("~/Images/image1.jpg");
           
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["ImageID"] = 2;
            dr["ImagePath"] = ResolveUrl("~/Images/image2.jpg");
            dt.Rows.Add(dr);
            dr = dt.NewRow();
       
            return dt;
        }
    }
}

In above code we have used TemplateCloumn of gridview and ImageField control inside it. Here we can set any datasource that contains image and bind it to gridview. Here in this example I have created sample datatable with image column and bind it to gridview to show image in gridview.

1 comment :

  1. I followed this tutorial by creating a table in the database where I stored the data of images in the stored table. After finishing with the code and running it I found the images being displayed successfully. Now thinking to modify this application to have more impressive output.

    ReplyDelete