Monday, October 04, 2004

Change image on condition in Datagrid

In my ASP.NET pet project,there is a page where list of users is shown in a datagrid. I wanted to have one column showing active status of users. I mean, if user is 'active' the grid will show color image. Similarly, if user is inactive, it should be represented by gray version of same image. Google was not able to find the solution(may be, search word was wrong). There was one forum where question was asked for this kind of functionality. Sad but truth, there was NO answer. So, I moved forward with other work in same project. After few days, while I was working with Repeater control, I had to look into it's help. My eyes stopped at a sample code for ItemDataBound event. That code gave me an idea to change column value at runtime. What you will see below is a code to show image in datagrid's column which change according to condition. First, insert an image in itemtemplate section in .aspx as shown below;

      <asp:image id="imgActiveStatus" runat="server"/>
Then, write a code for ItemDataBound even for grid as below;

if (e.Item.ItemType = ListItemType.Item) Or
   (e.Item.ItemType = ListItemType.AlternatingItem) then
    if DataBinder.Eval(e.Item.DataItem,'Active').ToString = 'True' then
      (e.Item.FindControl('imgActiveStatus') as Image).ImageUrl := 'images/user_active.gif'
      (e.Item.FindControl('imgActiveStatus')as Image).ImageUrl := 'images/user_inactive.gif';


Anonymous said...

Thanks really helped me.

Saved me alot of time.


Anonymous said...

Cool blog as for me. I'd like to read more about this matter. Thanx for sharing that info.
Sexy Lady
English escort