I have a repeater that displays data from my Projects table. There are projectId, name and description. I use Substring(1, 240) on description. But sometimes the string is s
string dec = "description";
string result = dec.Substring( 0, dec.Length > 240 ? 240 : dec.Length )
An extension method:
public static string SafeSubstring(this string text, int start, int length)
{
if (start >= text.Length)
return "";
if (start + length > text.Length)
length = text.Length - start;
return text.Substring(start, length);
}
Let's try to keep this simple...
We only need to truncate to a given max length, so how about we call it what it is:
description.TruncateTo(240);
The extension method that enables the above (ellipsis is appended by default if truncated):
public static class StringExtensions
{
public static string TruncateTo(this string val, int maxLength, bool ellipsis = true)
{
if (val == null || val.Length <= maxLength)
{
return val;
}
ellipsis = ellipsis && maxLength >= 3;
return ellipsis ? val.Substring(0, maxLength - 3) + "..." : val.Substring(0, maxLength);
}
}
Based on Jon Skeet's answer, I think it should be checking for null or else it's not exactly a safe method :)
public static string SafeSubstring(this string text, int start, int length)
{
if (text == null) return null;
return text.Length <= start ? ""
: text.Length - start <= length ? text.Substring(start)
: text.Substring(start, length);
}
Text='<%# Eval("Description").ToString().Substring(1, Math.Min(240, Eval("Description").ToString().Length - 1)) + "..." %>'