Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image based on a value in asp GridView column

I have a gridview and one of the template fields is an asp image server tag. I want to display an image in this gridview but based on the value that I obtain on databind.

So, every row can have a different values and based on these values I need to display different images. I tried to call a javascript function GetImage() and pass the value that I obtain on databind to this function. But, I cannot get this to work.

 <Columns>
      <asp:TemplateField HeaderText="<%$Resources:LocalizedText,LabelStatus%>">
           <ItemTemplate>
                <asp:Image ID="imgStatus" runat="server" CssClass="label" src="GetImage(<%#Eval(<%# Bind("Status_value")  %>) %>)"/>
           </ItemTemplate>
      </asp:TemplateField>
  </Columns>

Javascript function -

function GetImage(value)
{
    if (value == 1)
    {
        return "../Images/act_green.gif";
    }
    else
    {
        return "../Images/act_red.gif";
    }
}

What am I doing wrong here? And, how can I fix it? Thanks

like image 827
pavanred Avatar asked Feb 01 '11 12:02

pavanred


2 Answers

Unless you have more needs that you haven't mentioned, there is no need to use Javascript and you might as well do everything on the server.

Change your asp:image tag to the following:

<asp:Image ID="imgStatus" runat="server" CssClass="label" ImageURL='<%# GetImage((int)Eval("Status_Value")) %>' />

In your code-behind, place the following:

public static string GetImage(int value)
{
    if (value == 1)
    { 
        return "../Images/act_green.gif";
    }
    else
    {
        return "../Images/act_red.jpg";
    }
}

And you're done.

like image 134
NakedBrunch Avatar answered Oct 30 '22 14:10

NakedBrunch


Your GetImage function is not executed.

See: IMG SRC tags and JavaScript


Server side code can return the path to the image without using JS.

like image 26
msms Avatar answered Oct 30 '22 13:10

msms