Conditional Binding Expression with ASP.NET GridView
By | September 11, 2011

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.

image thumb3 Conditional Binding Expression with ASP.NET GridView

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

image thumb4 Conditional Binding Expression with ASP.NET GridView

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

image thumb5 Conditional Binding Expression with ASP.NET GridView

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.

image thumb6 Conditional Binding Expression with ASP.NET GridView

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.

image thumb7 Conditional Binding Expression with ASP.NET GridView

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

image thumb8 Conditional Binding Expression with ASP.NET GridView 

Hope this helps !

Cheers !

Aj