This Gridview sample shows how to, for each row, based on other data within that row, to show a different image. We do this by creating a TemplateField, and putting an ASP.Net Image control within it, called ‘Image1′.
Then, inside the RowDataBound event of the Gridview, we put code, which first, checks and finds the Image control in that row, and then assigning a different JPG file to the ImageURL property of that image. One other thing here, you’ll notice, is that when the criteria is matched, we set the Image control’s Visible property to ‘True’. That’s because, one extra criteria is, that if the Units In Stock is larger than 80, we set the Image control’s Visible property to ‘False’.
Naturally, since we’re checking one particular column in the Gridview for this data, we’re using a Select Case statement.
<script language="VB" Runat="server">
Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim img As Image = CType(e.Row.FindControl("image1"), Image)
Select Case cInt(e.Row.Cells(3).Text)
Case 0
img.ImageUrl = "/images/red.jpg"
img.Visible=True
Case 1 to 25
img.ImageUrl = "/images/yellow.jpg"
img.Visible=True
Case 26 to 80
img.ImageUrl = "/images/green.jpg"
img.Visible=True
Case > 80
img.Visible=False
End Select
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Conditional Gridview Images</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="ds1" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HtmlEncode="False"
HeaderText="UnitPrice" SortExpression="UnitPrice" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="ds1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitsInStock], [UnitPrice] FROM [Products]">
</asp:SqlDataSource>
</form>
</body>
</html>