Conditional Binding Expression with ASP.NET GridView

ASP.NET GridView provides the flexibility to use  conditional binding expression where we can use some condition with bind expression. Depends on the evaluation value of the expression, ASP.NET GridView will render the content on page. In this tip I am going to explain one such scenario where the actual data source containing some status value which is a Boolean, but instead on Boolean, we will bind status image in a template field.

Let’s consider we have below class which represent the customer entity.


Below code snippet demonstrating a creation of a data source which contains list of customers and binding with GridView Control.


Press F5 and run the application. Below images resulting the current output.


What we can see from the above output is Active account field  render as “CheckBox” . In our data source “ActiveAccount” is a type of Boolean field and this is how ASP.NET GridView renders the Boolean type while direct binding.

Let’s come a the point, instead  of the “CheckBox” you want this field should be an image which will represent the Active and Inactive Status of the Customer.  Now as part of this assignment,  We will be changing GridView to custom Template and below is the snippet for the same.


You can see, ImageURL is left as blank.we can not  bind the “ActiveAcount” field as image URL  as it is a Boolean field. Let’s also assume that, the image name are “Active.png” and “Inactive.png” . So, what we want is, instead of true and false, our image field should bind “active.png” or “inactive.png” respectively.

In this kind of scenarios where we need to take control of field inside of Template field, the first thing that any developer can think of one of the most post powerful event “RowDataBound”. Where we  can use “FindControl” method to get the “image” field and we can apply any images based on the value of “ActiveAccount”.  But, this time I am not going to do that. Let’s do it from Markup itself. 

Below code snippet shows the using conditional expression binding with the image url field.


First of all, Eval(“ActiveAcount”) will return the result either in true or false, based on the value a conditional operator pickup the value either Active and Inactive as string. Finally I am containing the images path and extension. That’s all. Below is the resulting output


Hope this helps !

Cheers !


Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.