Mark Kadlec
Mark Kadlec

Reputation: 8440

How to dynamically show images in a asp.net gridview?

I have a gridview that has a column that currently returns a "1" if there was a signoff, or 0 if not. I would like to show a "Thumbs up" image if the value is 1 for each row, or nothing if 0.

What is the best method for doing this? I was thinking of somehow using the rowdatabound event, what is the best way to do this?

Thanks,

Mark.

Upvotes: 0

Views: 14110

Answers (5)

Mark Kadlec
Mark Kadlec

Reputation: 8440

Thanks guys, I ended up doing it with a boundfield -> rowdatabound solution.

I already had databound event code happening so I just added to it. I put an imagebutton control on there and looks good now (a little off center, but I guess it's better than before).

Thanks for the suggestions,

Mark.

Upvotes: 0

Jeremy
Jeremy

Reputation: 3893

This is a little messy, but it's all contained in the template tag:

<ItemTemplate>
  <img src='<%# (bool)Eval("signoff") ? "thumbsup" : "thumbsdown" %>.gif' alt="whatever" width="16" height="16" />
</ItemTemplate>

Hope this helps!

Upvotes: 1

patjbs
patjbs

Reputation: 4772

The rowdatabound event certainly provides you with the ability to do this. It's fairly straight forward and intuitive to do so. And as mark mentioned, you could use a template column. I'd probably just use either the template column, or an image field to manage this:

<Columns>
    <asp:ImageField HeaderText='Sign Off' 
        DataImageUrlField='<%# ThumbDisplay(Eval("SignOff")) %>' />
</Columns>

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

protected string ThumbDisplay(int signoff)
{
    return (signoff == 1) ? "~\thumbsup.png" : "~\thumbsdown.png";
}

http://www.asp.net/learn/data-access/tutorial-12-cs.aspx has good detail on using the template column.

The best method is probably the one that fits with your other display needs. Will other columns need similar massaging? You might be better off taking care of it all in one go in the rowdatabound event. But if it's going to be your only modification to the data, using a template column, or the image column, will probably be the easiest to follow and keep the whole page clean.

Upvotes: 2

Mark Brittingham
Mark Brittingham

Reputation: 28865

Another approach that is quite flexible is to use a template column. This gives you a lot of freedom. For example, you can use the value of your column to toggle the arguments to an img tag (or to toggle between two img tags) and/or specify arguments to a link.

I've always found template columns quite straightforward.

Upvotes: 2

Robin Clowers
Robin Clowers

Reputation: 2160

You should be able to use an image column and bind the url to a method that take the 1 or 0 and returns the correct image url. See http://msdn.microsoft.com/en-us/library/aa479350.aspx.

Upvotes: 1

Related Questions