Search code examples
asp.netimagegridvieweval

picture inside a grid view according to some value in asp.net


I got a field status has three value : 0 pendding 1 accept 2 refuse

i want to add it on grid view but with image instead of numbers :

if 0  select.png
if 1  ok.png
if 2  no.png

i tried this code but didnt see the picture :

 <asp:Image ID="Image1" runat="server" ImageUrl='~/img/<%# (Eval("id") == "1") ? "ok.png" : "" ; %>'></asp:Image>   

what should i do ?? and how to add three condition ?


Solution

  • You can do this in two different way:-

    1st Way:-- Use the TemplateColumn instead of bound column, and include <asp:image> control in it. And then add the OnRowDataBound event to Grid.

    Then attach your Images, based on your if statement.

    Sample Code under GridView_RowDataBound event

    if (e.Row.RowType == DataControlRowType.DataRow)
       {
           Image i = (Image)e.Row.FindControl("image");
           //include your if statement here, and set ImageUrl
           i.ImageUrl = "select.png";
        }
    

    2nd Way Add ImageField in GridView under Template Column

    <asp:Image HeaderText='Status' 
            ImageUrl='<%# ImageDisplay(Eval("Status").ToString()) %>' />
    

    and You'd then need a method like the following in your codebehind:

    protected string ImageDisplay(string status)
    {
         ///write you if condition and return image path url
          //return "~\select.png";
    }