ASP.NET DataBinder Eval examples1. Dynamically enable a control based on datasource valueThe following formats are correct.
Enabled='<%# Eval("FeatureLink")=="Y" ? true : false %>'
Enabled='<%# Eval("FeatureLink", "{0}").ToLower()=="y" ? true : false %>'
Enabled='<%# Eval("FeatureLink").Equals("Y") %>'
You need to check whether the eval is null before testing it if there is a null object reference exception.
Enabled='<%# Eval("FeatureLink")==null ? false : Eval("FeatureLink").Equals("Premium") %>'
Note that Enabled="<%# false %>" should be simplified as Enabled="false" in spite of no syntax error.
Two points here: 1) Eval must be in single quotes; 2) boolean type true or false must be used if using C# ternary syntax; You can use == or Equals to compare strings. This is different from "== here will not compare the string contents, but the string objects. So, instead, you must use .Equals()" commented
here.
Note the following formats don't work.
Enabled="<%# Eval("FeatureLink").Equals("Y") %>" -> The server tag is not well formed
If the datasource value is "true" or "false" instead of "Y" or "N",
Enabled='<%# Eval("FeatureLink") %>' -> InvalidCastException
Enabled="<%# Eval("FeatureLink") %>" ->The server tag is not well formed
The C# ternary syntax that doesn't work.
Enabled="<%# Eval("FeatureLink")=="Y" ? "true" : "false" %>" ->The server tag is not well formed
Enabled="<%# Eval("FeatureLink")== null ? "false" : "true" %>" ->The server tag is not well formed
Enabled='<%# Eval("FeatureLink")=="Y" ? "true" : "false" %>' -> Cannot convert type 'string' to 'bool'
2. Eval with string functions / methodsText='<%# Eval("MoreInfo", "{0}").Replace("\n", "<br/>") %>'
The format "{0}" must be used here. Otherwise Eval("MoreInfo") is an object not a string so it doesn't have the Replace() method. The same applies to other string functions such as ToLower() as mentioned in the first example above.
Text='<%# Eval("MoreInfo").Replace("\n", "<br/>") %> -> the object doesn't have Replace() method...
3. Eval that doesn't use datasource valueNavigateUrl="<%# Request.RawUrl %>"
Edited by user Thursday, 10 March 2016 7:52:08 AM(UTC)
| Reason: Not specified