Punit Sharma
Punit Sharma

Reputation: 11

How to display at most 250 character and the rest of the string as '.... {X} more words'

Here i want to count total characters while binding database and display only 250 characters and remaining like '....' 631 more words

by using c# code behind thanks.

Upvotes: 0

Views: 373

Answers (3)

Ben Reich
Ben Reich

Reputation: 16324

You might consider using an new extension method. The logic below will guarantee that you do not cut a word up in the middle, and that the "more words" part won't be included unless the string was actually cut off:

public static class Extensions
{
    public static string ToCutOffString(this string text, int maxLength)
    {
        var totalChars = 0;
        var words = text.Split(' ');
        var wordsToInclude = words.Where(word => (totalChars += word.Count()) < maxLength).ToList();
        var initialText = string.Join(" ", wordsToInclude);
        var numWordsExcluded = words.Count() - wordsToInclude.Count();
        var format = numWordsExcluded == 0 
                       ? "{0}" : "{0}... {1} more word" 
                       + (numWordsExcluded > 1 ? "s" : "");
        return string.Format(format, initialText, numWordsExcluded);
    }
}

And then you can use it like:

"very long string with many words".ToCutOffString(25);

Upvotes: 1

Debajit Mukhopadhyay
Debajit Mukhopadhyay

Reputation: 4172

To return correct "More words" you need to use this

 var numWordsExcluded = words.Count() - initialText.Split(' ').Length;

Upvotes: 0

skhurams
skhurams

Reputation: 2145

you can try it in your query

SELECT LEFT(ColumnName,250) + '...' + (DATALENGTH(ColumnName)-250) + ' more words' from TableName 

Upvotes: 0

Related Questions