Reputation: 195
This seems like a fairly straightforward problem but I keep getting the same exception and I have no idea why.
I can only assume that it has something to do with a misunderstanding of how substring works in VB.NET.
The following code, keeps throwing a ArgumentOutOfRange exception:
<%=Html.Encode(IIf(item.description.Length > 150, item.description.Substring(0, 150), item.description))%>
Now what should happen here is, if item.description is over a 150 characters output the first 150 otherwise output the entire string. Problem is it keeps trying to get the sub-string regardless of the length of the result of the if statement.
Any help would be greatly appreciated.
Upvotes: 0
Views: 392
Reputation: 16144
Try using:
Check this:IIf() vs. If
If(item.description.Length > 150) Then
item.description.Substring(0, 150)
Else
item.description
End If
OR,
If(item.description.Length > 150, item.description.Substring(0, 150), item.description)
Upvotes: 0
Reputation: 498914
When you use IIF
you evaluate all the expressions - the true as well as the false "branches".
This means that for strings that are under 150 characters long, you still call item.description.Substring(0, 150)
, causing the error.
Perhaps have an item.ShortDescription
which only ever return the first 150 characters, using a normal IF/THEN
.
Upvotes: 2
Reputation: 25013
Use the If(expression,truepart,falsepart) operator instead: the IIF operator attempts to evaluate both the true and false parts whereas the If operator only attempts to evaluate the relevant part.
Upvotes: 3