Tuesday, 13 April 2010

GridView: Switch Images in cells depending upon bound data


It is quite common to have a scenario where your storing a boolean in the database, and at the front end, you would like to render this as a tick or a cross. This is a very simple example, but this can be built upon to enable more complex scenarios...


1. Setup your datagrid with a template column...
<asp:TemplateField HeaderText="Enabled" AccessibleHeaderText="Enabled">
<ItemTemplate>
    <asp:Image ID="imgEnabled" runat="server" ImageUrl='<%# GetImageUrl((bool)Eval("Enabled")) %>' />
</ItemTemplate>
</asp:TemplateField>


In this example, were using a simple boolean. These can be custom objects as long as they are casted here and fully qualified with the namespace; so that the objects can be identified and the method can be paired.

Now, in the code behind, we need to add the logic to output this image URL.
/// <summary>
/// Provides an image URL for an enabled status.
/// </summary>
/// <param name="input">Enabled value</param>
/// <returns>A URL to the enabled icon</returns>
protected string GetImageUrl(string enabled)
{
    string result = string.Empty;
 
    if (enabled)
        result = "../images/icon-tick.gif";
    else
        result = "../images/icon-cross.gif";
 
    return result;
}


You can see that this method returns a string, this is accepted by the ImageUrl attribute where we placed the Eval statement. cool huh?

No comments: