ASP.NET 2.0 Quick Tip: Add a hyperlink to an image in a GridView column
I 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
Comments
Anonymous
October 05, 2006
You could also use the ImageUrl property of the HyperLink webcontrol instead of a nested Image webcontrol.rajAnonymous
October 05, 2006
Raj, that's very true; that would be even neater code. Thanks!Anonymous
November 04, 2006
http://www.blogging.co.uk/christmasgifts <a href="http://www.blogging.co.uk/christmasgifts">christmas gifts</a> christmas giftsAnonymous
November 12, 2006
http://pb2.forenshop.net/cgi-bin/forenserver/foren/F_2359/cutecast.pl <a href="http://pb2.forenshop.net/cgi-bin/forenserver/foren/F_2359/cutecast.pl">Christmas gifts</a> Christmas giftsAnonymous
November 23, 2006
http://forum.lixium.fr/cgi-bin/liste.eur?gifts <a href="http://forum.lixium.fr/cgi-bin/liste.eur?gifts">Christmas Gifts</a> Christmas GiftsAnonymous
December 03, 2006
This also could be done in code-behind dynamically. Perhaps sometimes better. Regards.