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
It's a bit of a hack, but the simplest method would be to change:
Eval("Description").ToString().Substring(1,240)
to
Eval("Description").ToString().PadRight(240).Substring(1, 240)
I'm not sure about the performance considerations on this, though, if therre are a lot of items.
Another option is to write a a method that you call so your eval turns into:
<%# GetString(Container.DataItem) %>
So in the method you could check to make sure that the item is NOT null because you may bomb out calling .ToString on a NULL item. Then you can evaluate the container item and pass in the length to the substring call.
You can use LINQ as below:
string someString = "abcde";
string subStr = string.Join("", someString.Take(240));
If you REQUIRE 240 characters in that place for some reason, you can cast that field coming out of the database as a char(241)
in which case it will always be 241 characters, with padding to the right if the content of the field was shorter than 241 characters. Then you can still strip off the first character with the Substring(1, 240)
as you are right now.
Although, I must wonder if you're not wanting to do a Substring(0, 240)
which wouldn't throw an exception if the string was shorter than 240 characters, and would start at the beginning of the string, rather than the 2nd character.
description.Substring(0, Math.Min(description.Length, 240));
I would suggest you write a separate extension method if you're using .NET 3.5. Something like this:
public static string SafeSubstring(this string text, int start, int length)
{
return text.Length <= start ? ""
: text.Length - start <= length ? text.Substring(start)
: text.Substring(start, length);
}
Basically that's a version of Substring
which will never throw an exception unless start or length is negative (in which case I don't know what it could sensibly return).
You'd call it like this:
Eval("Description").ToString().SafeSubstring(1, 240) + "..."
The downside of this is that it will include the ellipsis (...) even if it's not actually truncated the string at all...