ASP.NET 2.0 Quick Tip: Add a hyperlink to an image in a GridView column

ASP.NET 2.0I was asked today how to add a hyperlink to an image in an ASP.NET 2.0 GridView column, so that clicking the image will cause the browser to navigate to a different page.  I thought I'd post it in my blog, just in case anyone else is searching for this.

It's very easy to add Images to a GridView using an ImageField.  As far as I can tell, the ImageField column doesn't let you include a hyperlink over the image.

No problem.  Start by creating your ImageField column.  Then, convert it to a TemplateField.  (A quick way to do this is to click the quick action glyph for the GridView, select "Edit Fields," choose your ImageField on the left (as below), and then click "Convert to Template Field.")

Now, change to code view, and edit the ItemTemplate for the column so that it includes a hyperlink that surrounds the asp:Image.  Here's an example.  The code I added after converting to a TemplateField is bold.  

Note that for simplicity, I am having all of the images navigate to the About.aspx page, but you could easily databind the NavigateUrl by mimicing the syntax used to bind the ImageUrl in the line below.  That way, each row's image could potentially navigate to a different URL.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="gridview" DataKeyNames="MosaicId" DataSourceID="ObjectDataSource1">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:CheckBoxField DataField="Sold" HeaderText="Sold" SortExpression="Sold" />
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("ThumbnailPhotoUrl") %>'></asp:TextBox>
</EditItemTemplate>

            <ItemTemplate>
< asp:HyperLink ID="HyperLink1" NavigateUrl="~/About.aspx" runat ="server">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ThumbnailPhotoUrl") %>' />
</ asp:HyperLink >
</ItemTemplate>

        </asp:TemplateField>
</Columns>
</asp:GridView>

Hope that helps,
Rob