0

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.

1
  • We're not automatic syntax highlighters to determine which language is it Commented Nov 26, 2009 at 1:50

3 Answers 3

6

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))%>
Sign up to request clarification or add additional context in comments.

1 Comment

You're missing a closing parenthesis. ;)
4

You could also do something like

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

to save some bytes

Comments

2
<%= 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))%>

2 Comments

Indexes are 0 based, while .Length is 1 based. >= won't work in this case. Use > instead.
Thanks folks for all of the replies. Pardon me but what if the string is null?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.