wiredlime2015
wiredlime2015

Reputation: 123

Conditional Image Template Column

I am using Visual Studio 2015 and entity framework 6. I have a GridView and I want the status column on it to show four different types of images, depending on string in that field from the database. I want it to be done with a template.

Here is my GridView:

<asp:GridView ID="gvStatus" runat="server" Height="184px" 
        Width="1359px"  AutoGenerateColumns="false" AllowSorting="true" >
    <HeaderStyle Font-Bold="true" Font-Size="16pt" BackColor="#cc0000" ForeColor="Black"/>
    <RowStyle Font-Size="12pt" BackColor="#afadad" ForeColor="White"/>
    <AlternatingRowStyle BackColor="#afadad" ForeColor="White" />

    <Columns>
        <asp:CommandField HeaderText="" SelectText="Delete" ShowSelectButton="true" ControlStyle-ForeColor="White"   />   
        <asp:BoundField HeaderText="Status" DataField="Status"  />    
    </Columns>
</asp:GridView>

How do I get the status column to show up with four different images, dependent on what string is there?

Upvotes: 1

Views: 82

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39966

You could do it like this:

<Columns>
    <asp:TemplateField >
        <HeaderStyle Width="10%" />                               
        <ItemTemplate>   
            <asp:Image  ID="Image1" runat="server" ImageUrl='<%#GetImagePath(Eval("img").ToString())%>' />                  
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

And in the code behind:

public string GetImagePath(object value)
{
    if (string.IsNullOrEmpty(Convert.ToString(value))) return string.Empty;
    var x = int.Parse(value.ToString());
    return x > 0 ? "Your Image Path" : "Default Image Path";
    //Here I show two different types of images depending on int value in that field from the database you can change it to four type with if-else and also depending on string value
}

Upvotes: 1

Related Questions