tags:

views:

63

answers:

3

how can I limit the # of characters to display for html.encode?

<%= Html.Encode(item.LastName.Substring(1,30))%>

error: Index and length must refer to a location within the string.

+6  A: 

You need to check the strings length is greater than 30, otherwise you are specifying a length which will fall off the end of the string...(I've also changed your start index to 0 assuming you didn't mean to leave out the first character)

<%= Html.Encode(item.LastName.Substring(0, 
                     item.LastName.Length > 30 ? 30 : item.LastName.Length))%>
Simon Fox
You're missing a closing parenthesis. ;)
Andy West
Thanks, fixed..
Simon Fox
+2  A: 
<%= Html.Encode(item.LastName.Substring(0, item.LastName.Length > 30 ? 30 : item.LastName.Length))%>

If you want to check for null, do this instead:

<%= Html.Encode(
item.LastName == null ? string.Empty :
item.LastName.Substring(0, item.LastName.Length > 30 ? 30 : item.LastName.Length))%>
Andy West
Indexes are 0 based, while .Length is 1 based. >= won't work in this case. Use > instead.
Kyle Trauberman
Ah, yes. Thank you. Fixed.
Andy West
Thanks folks for all of the replies. Pardon me but what if the string is null?
dmarkez
Please see the edit in my post for how to deal with null.
Andy West
Fantastic! thanks all for the help.
dmarkez
+4  A: 

You could also do something like

<%= Html.Encode(item.LastName.Substring(0, Math.Min(item.LastName.Length, 30)) %>

to save some bytes

Marek Karbarz