GridView Examples for ASP.NET 2.0: Displaying Images in a GridView Column

 

Click here to return to the TOC.

In the ASP.NET 1.x class I teach, the course-long project for the students is to create an online photo album, one that allows visitors to upload images and provide metadata about the images, such as a description, a title, and so on. The data model my students typically use consists of a Pictures table with the following fields:

  • PictureID—a synthetic primary key, typically an integer field setup as an IDENTITY.
  • Title—a short title for the picture.
  • DateAdded—the date/time the picture was uploaded.
  • PictureUrl—the path to the uploaded image file.

When users want to add a new image to the photo album site, they must visit a particular page that contains a file upload control along with form input fields querying them for the other bits of information. When they submit the form, the picture on their computer is uploaded to the Web server's file system and a new row is added to the Pictures table. The PictureUrl field is set to the virtual path of the uploaded image file.

There's an additional page that lists all pictures in the photo album using a DataGrid. To display an image in a column in a DataGrid in ASP.NET 1.x you have to use a TemplateColumn with an Image Web control inside the TemplateColumn. With ASP.NET 2.0 the GridView includes an ImageField that can be used to display an image in a column of the GridView.

Imagine that we had the data model discussed previously and wanted to display all of the pictures in a GridView, displaying the PictureID, Title, and DateAdded fields each in a column and the actual image itself in an additional column.

To accomplish this we'd first grab the data using a data source control and then add a GridView bound to that data source control. This GridView would have four BoundField columns, meaning that instead of seeing the actual image we'd see the actual image path when viewing the GridView in a browser. To display the actual image, we need to edit the GridView's columns, removing the PictureUrl BoundField and replacing it with an ImageField. To edit a GridView's columns simply click on the Edit Columns link from the GridView's Smart Tag. This will bring up a dialog box like the one shown in Figure 25. Delete the PictureUrl BoundField and add in an ImageField. Finally, set the ImageField's DataImageUrlField to the name of the DataSource field that contains the image path—PictureUrl.

Aa479350.gridview_fg25(en-us,MSDN.10).gif

Figure 25

This will result in a GridView with the following declarative syntax:

<asp:GridView ID="GridView1" Runat="server" 
  DataSource='<%# GetData() %>' AutoGenerateColumns="False" 
  BorderWidth="1px" BackColor="White" CellPadding="3" BorderStyle="None" 
  BorderColor="#CCCCCC" Font-Names="Arial">
    <FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
    <PagerStyle ForeColor="#000066" HorizontalAlign="Left" 
      BackColor="White"></PagerStyle>
    <HeaderStyle ForeColor="White" Font-Bold="True" 
      BackColor="#006699"></HeaderStyle>
    <Columns>
        <asp:BoundField HeaderText="Picutre ID" DataField="PictureID">
            <ItemStyle HorizontalAlign="Center" 
              VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
        <asp:BoundField HeaderText="Title" DataField="Title"></asp:BoundField>
        <asp:BoundField HeaderText="Date Added" DataField="DateAdded" 
          DataFormatString="{0:d}">
            <ItemStyle HorizontalAlign="Center"></ItemStyle>
        </asp:BoundField>
        <asp:ImageField DataImageUrlField="PictureURL"></asp:ImageField>
    </Columns>
    <SelectedRowStyle ForeColor="White" Font-Bold="True" 
       BackColor="#669999"></SelectedRowStyle>
    <RowStyle ForeColor="#000066"></RowStyle>
</asp:GridView>

Since the Northwind database does not have a table with an image path, we'll have to programmatically create our own data model to see this demo in action. The following code in our ASP.NET page creates a DataTable with the appropriate schema and populates the DataTable with four records.

Creating a DataTable Programmatically (Visual Basic)

Function GetData() As DataTable
    ' This method creates a DataTable with four rows.  Each row has the
    ' following schema:
    '   PictureID      int
    '   PictureURL     string
    '   Title          string
    '   DateAdded      datetime
    Dim dt As New DataTable()
    ' define the table's schema
    dt.Columns.Add(New DataColumn("PictureID", GetType(Integer)))
    dt.Columns.Add(New DataColumn("PictureURL", GetType(String)))
    dt.Columns.Add(New DataColumn("Title", GetType(String)))
    dt.Columns.Add(New DataColumn("DateAdded", GetType(DateTime)))
    ' Create the four records
    Dim dr As DataRow = dt.NewRow()
    dr("PictureID") = 1
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Blue hills.jpg")
    dr("Title") = "Blue Hills"
    dr("DateAdded") = New DateTime(2005, 1, 15)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 2
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Sunset.jpg")
    dr("Title") = "Sunset"
    dr("DateAdded") = New DateTime(2005, 1, 21)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 3
    dr("PictureURL") = _
      ResolveUrl("~/DisplayingImages/Images/Water lilies.jpg")
    dr("Title") = "Water Lilies"
    dr("DateAdded") = New DateTime(2005, 2, 1)
    dt.Rows.Add(dr)
    dr = dt.NewRow()
    dr("PictureID") = 4
    dr("PictureURL") = ResolveUrl("~/DisplayingImages/Images/Winter.jpg")
    dr("Title") = "Winter"
    dr("DateAdded") = New DateTime(2005, 2, 18)
    dt.Rows.Add(dr)
    Return dt
End Function

Creating a DataTable Programmatically (C#)

DataTable GetData()
{
    // This method creates a DataTable with four rows.  Each row has the
    // following schema:
    //   PictureID      int
    //   PictureURL     string
    //   Title          string
    //   DateAdded      datetime
    DataTable dt = new DataTable();
    // define the table's schema
    dt.Columns.Add(new DataColumn("PictureID", typeof(int)));
    dt.Columns.Add(new DataColumn("PictureURL", typeof(string)));
    dt.Columns.Add(new DataColumn("Title", typeof(string)));
    dt.Columns.Add(new DataColumn("DateAdded", typeof(DateTime)));
    // Create the four records
    DataRow dr = dt.NewRow();
    dr["PictureID"] = 1;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Blue hills.jpg");
    dr["Title"] = "Blue Hills";
    dr["DateAdded"] = new DateTime(2005, 1, 15);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 2;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Sunset.jpg");
    dr["Title"] = "Sunset";
    dr["DateAdded"] = new DateTime(2005, 1, 21);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 3;
    dr["PictureURL"] = 
      ResolveUrl("~/DisplayingImages/Images/Water lilies.jpg");
    dr["Title"] = "Water Lilies";
    dr["DateAdded"] = new DateTime(2005, 2, 1);
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr["PictureID"] = 4;
    dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Winter.jpg");
    dr["Title"] = "Winter";
    dr["DateAdded"] = new DateTime(2005, 2, 18);
    dt.Rows.Add(dr);
    return dt;
}

To bind this data to the GridView we can set the GridView's DataSource property to the GetData() method like so:

<asp:GridView Runat="server" DataSource='<%# GetData() %>' ...>
  ...
</asp:GridView>

Finally, we need to call Page.DataBind() in the Page_Load event handler to bind the GridView's DataSource.

Page_Load Event Handler (Visual Basic)

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Page.DataBind()
End Sub
Page_Load Event Handler (C#)
void Page_Load(object sender, EventArgs e)
{
    Page.DataBind();
}

The end result is a GridView that shows the image referenced by the PictureUrl path (see Figure 26).

Aa479350.gridview_fg26(en-us,MSDN.10).gif

Figure 26

Don't be daunted by the length of this example's code—the length is due entirely to the fact that we had to synthetically create a data model with a table that has an image path field. Had the Northwind database had such a table, this example—like the previous ones—wouldn't have required a lick of code.

Next Section: Working with TemplateFields

© Microsoft Corporation. All rights reserved.