kev670
kev670

Reputation: 880

ASP.NET Gridvgiew. Swap string for image

I'm using gridview and I'm displaying data from a database into it using boundfield within the gridview.

2 of the columns in the gridview only display a YES or a NO value. I would like to swap the YES or NO out for a green tick image or a red X image... Can anyone help me out with this or point me to a similar solution. I use c#

Upvotes: 0

Views: 418

Answers (5)

R.D.
R.D.

Reputation: 7403

code to be used on aspx page:

  <asp:TemplateField HeaderText="Image">
      <HeaderStyle BackColor="#FFD653" Width="10%" HorizontalAlign="Center" />                               
      <ItemTemplate>                         
          <img src='<%#GetImagePath(Eval("databasecolumnvalue").ToString())%>'/>
      </ItemTemplate>
      <ItemStyle HorizontalAlign="Center"  />
  </asp:TemplateField>

Code to be used on cs file

 public void GetImagePath(object value)
  {
    if(!string.IsNullOrEmpty(Convert.ToString(value)))
      {
         if(Convert.ToString(value)=="Yes")
             return "yes image url";
         else if(Convert.ToString(value)=="No")
             return "no image url";
      }
   }

Upvotes: 1

DarkRaven
DarkRaven

Reputation: 13

You could have an image with the runat="server" attribute and change the src in your code-behind, in the RowDataBound event.

For example :

<ItemTemplate><img id="theImage" runat="server" /></ItemTemplate>

And in the code-behind :

Control ctl = e.Row.Cells[0].FindControl("theImage");
HtmlControl htmlCtl = ctl as HtmlControl;

if (htmlCtl != null)
{
    String image = ((DataRowView)e.Row.DataItem)[0] as String == "YES" ? "images/accept.png" : "images/cancel.png";
    htmlCtl.Attributes["src"] = image;
}

Upvotes: 0

codingbiz
codingbiz

Reputation: 26386

You can also try this

<asp:TemplateField>
<ItemTemplate>
    <%= Eval("Field") == "Yes" ? "<img src='tick.png' />" : "<img src='cross.png' />" %>
</ItemTemplate>
</asp:TemplateField>

Upvotes: 0

huMpty duMpty
huMpty duMpty

Reputation: 14470

Use TemplateFields to populate your gridview

Where the field you have yes, no values, pass the <%# Eval("YourValue") %> to a method which return the path of image you need to use

eg

public static string GetImage(string value)
{
    var str = "default image url";
    if(!string.IsNullOrEmpty(value))
    {
    if(value=="Yes")
          str = "yes image url";
    else if(value=="No")
          str = "no image url";
    }
    return str;
}

Upvotes: 1

Mayank Pathak
Mayank Pathak

Reputation: 3681

Make a public function in your code behind and that should be accepting string type parameter and use that public function on your design/.aspx page and check in Public function if it's yes then return

<img src='path of your Green tick image' />

else return

<img src='path of your red X image' />

But you won't be able to use this public function on bound fields...you'll have to use template field for that

Upvotes: -1

Related Questions