Im using a repeater control and a databinder to display data from the database to my website. example: DataBinder.Eval(Container, "DataItem.title")
Sometimes the text is too long Normally I use substring to 开发者_运维知识库display the preferred string in length. But How do I do this with the databinder And if the text is too long (> 20 characters) I want to truncate it and leave three dots behind. How to do that ?
I'd suggest an extension method to do the heavy lifting, in order to make the markup as simple as possible:
public static string EvalTrimmed(this RepeaterItem container, string expression, int maxLength)
{
string value = DataBinder.Eval(container, expression) as string;
if ( value != null )
return null;
if (value.Length > maxLength)
value = value.Substring(0,maxLength) + "...";
return value;
}
Then use it in markup as:
<%# Container.EvalTrimmed("DataItem.Title", 20) %>
If you're using the baked in ASP.net Repeater control then one answer would be to handle the Repeater.ItemDataBound
event. If it's another, 3rd party, repeater control then it'll probably expose a similar event that you can handle to achieve the same effect.
You can then trim the text that's being passed to DataBinder.Eval to the number of required characters and tack some ellipses onto the end.
精彩评论