<% if(Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES) { %>
...
<% } else { %>
...
<% } %>
Gives me a InvalidOperationException? How do I write conditional html generation in ASP?
Use an inline statement as John_ states, or, create a function in your code behind that performs the logic required.
protected string MyFunction(int nbrOrders)
{
if(nbrOrders>=Config.MAX_ENQUIRY_SALES)
{
return "TrueResult";
}
else
{
return "FalseResult";
}
}
Then use this as follows
<%# MyFunction(Convert.ToInt32(Eval("NbrOrders"))) %>
EDIT: I've just read a comment on another post that states you want to show different HTML depending on this result. In that case, you can try using the Visible flag of a placeholder containing your code. Such as:
<asp:PlaceHolder id="PlaceHolder1" runat="server" visible='<%# (Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES)%>'>
<div>My True Html Here</div>
</asp:PlaceHolder>
<asp:PlaceHolder id="PlaceHolder2" runat="server" visible='<%# !(Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES)%>'>
<div>My FalseHtml Here</div>
</asp:PlaceHolder>
I'm not sure you can add brackets for the conditional binding, the only way I know of doing it is with an inline statement like so:
<%# Convert.ToInt32(Eval("NbrOrders"))>=Config.MAX_ENQUIRY_SALES) ? Eval("IfTrueValue") : Eval("IfFalseValue") %>
The problem with @Robin Day's answer is that the following code fails if you have databound children that may or may not have data given the current state of whatever you are rendering. Sometimes it's difficult to maneuver around nullable databound code if you have a complex object graph.
For example, consider:
<asp:PlaceHolder runat="server" Visible="<%# VisibleCondition() %>">
<%# ((string)null).ToString("c") %> //an object that may have null data
//given the visible condition
</asp:PlaceHolder>
If VisibleCondition()
returns false
, child controls still get called with DataBind()
which can result in a NullReferenceException
in the example above.
Here is a better approach, IMHO:
public class ConditionalPlaceHolder : PlaceHolder
{
protected override void DataBindChildren()
{
if( this.Visible )
{
base.DataBindChildren();
}
}
}
And used in the following way:
<web:ConditionalPlaceHolder runat="server" Visible="<%# VisibleCondition1() %>">
//whatever databound code
<%# ((string)notNullGivenVisibleCondition1).ToString() %>
<p>But could be given visible condition 2</p>
</web:ConditionalPlaceHolder>
<web:ConditionalPlaceHolder runat="server" Visible="<%# VisibleCondition2() %>">
//whatever databound code
<%# ((string)notNullGivenVisibleCondition2).ToString() %>
<p>But could be given visible condition 1</p>
</web:ConditionalPlaceHolder>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With