<div runat="server" visible='<%# !String.IsNullOrEmpty(Eval("MyProp") as string) %>'> <%# Eval("MyProp") %> </div>
Change 2010/9/30
Now that I have some time, I feel that I have to expand my answer. Especially considering that this question is a duplicate that already has a better answer than my original. Therefore, I will consider the first part of your question:
Why can't you combine if and eval? The reason is that code blocks <% ... %> are executed during the visualization phase of the page life cycle. ASP.NET puts your code (an if statement in this case) into a function, then passes that function as a delegate to SetRenderMethodDelegate . The problem is that Eval evaluates your "MyProp" expression on the object returned by Page.GetDataItem . Page.GetDataItem is a little magic that returns a value only if there has previously been a DataBind call in the call stack. By the time the visualization phase begins, all data bindings are complete. Therefore, when you call Eval, which implicitly calls Page.GetDataItem, the following error occurs: "Data binding methods [...] can only be used in the context of managing data binding."
So, code blocks <% ... %> will not work, but what about code blocks <%# ... %> , aka data binding expressions ? Data binding expressions are executed in the desired part of the page life cycle - in the DataBind call. However, the operative word here is an expression. The if not an expression. Anything you choose between <%# ... %> will be evaluated by the compiler as an expression. If you place the instruction there, the compiler throws an error.
Therefore, we arrive at the idiom of calling Eval in an expression that binds data using the Visible property of the control. Eval is compatible with data binding expressions; write an expression enough to assign a property value; and the Visible property can achieve an effect similar to the effect of using the built-in if . One final tip: if you ever find yourself in a situation where you donβt have any existing control to naturally add a Visible condition, you can always use <asp: PlaceHolder> - a control that does not add any markup to the markup.
source share