how to use conditions and string formatting in Eval statement in ASP.Net

5:36:00 am 0 Comments

Abstract: Here Al-Salman Rahman has explained how to use conditions and string formatting in Eval statement in ASP.Net 
There are many occasions when you want to have some conditions and also string formatting with Eval, it would be nice to do it in the ASPX page itself but many developers don’t know the syntax and hence I decided to write on this topic. In this article I will explain you how to use string formatting and conditions in the Eval statement of ASP.Net.

Conditions using Eval
Consider a case where I have an old database with old city names hence I need to replace “Bombay” with “Mumbai”, so here’s what I need to do.
<asp:Label ID="Label1" runat="server" Text='<%# Eval("City").ToString() == "Bombay" ? "Mumbai": Eval("City") %>'></asp:Label>

Another is a case where I want to append the Salutation or title as prefix to the names based on gender of the person
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Gender").ToString() == "Male" ? "Mr." + Eval("Name") : "Ms." + Eval("Name") %>'></asp:Label>

We can also control the Visible and Enabled property of a control using Eval in the following way
<asp:Label ID="Label1" runat="server" Text= "Is Available" Visible = '<%# (bool)Eval("IsOnline") %>'></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" Enabled = '<%# (bool)Eval("IsOnline") %>' />
 
String formatting using Eval
You can also use Eval for formatting strings in following way
Below I am appending Dr. as prefix to the name of all Doctors
<asp:Label ID="Label1" runat="server" Text= '<%# Eval("DoctorName", "Dr.{0}") %>'></asp:Label>

You can also use Eval to build URLs for Hyperlinks in following way
<asp:HyperLink ID="HyperLink1" runat="server" Text = "Download" NavigateUrl = '<%# Eval("DocumentId", "~/Downloads.aspx?DocumentId={0}") %>'></asp:HyperLink>
 
That’s it from me in this article. If there’s anything that left out and you want that to be added kindly let me know.

0 comments: