4

I have this line in my code-behind:

lblAboutMe.Text = (DT1["UserBody"].ToString());

No problems. But now, we want to only show the beginning of the paragraph and then an ellipsis. So, instead of being:

Please read it all as I hate wasting time with people that don't. If you have an issue with Muslim's please move on as I do not. I used to practice Islam and while I no longer do I still respect it and hate the ignorance people show by following the media or stigma instead of experiencing it or talking with Muslim's to educate themselves about it. Referring to the no drug policy later in this profile, yes, pot/marijuana counts as a drug and is a no with me so please move on. I know what follows makes me seem cold but I am really quite warm and loving, very devoted to the right one, i am just tired of being played and taken for granted/ advantage of. People lie soooo much and ignore so much of what I say I do not want. I have been told many times on here that what I seek is too much.

We want to take just the first, say, 100 characters and follow it with an ellipsis. So, something like:

Please read it all as I hate wasting time with people that don't. If you have an issue with Muslim's please move on as I do not. I used to practice Islam and while I no longer do I still respect it and hate the ignorance people show by following the media or stigma instead of experiencing it or talking with Muslim's to educate themselves ...

How can we do this in code-behind? I have a feeling it's pretty easy (because it would be easy in Access), but I'm still new to this language.

sgowd
  • 946
  • 3
  • 10
  • 27
Johnny Bones
  • 8,786
  • 7
  • 52
  • 117
  • 2
    http://stackoverflow.com/questions/3800962/ellipsis-with-c-sharp-ending-on-a-full-word – halit Jan 29 '16 at 06:18

4 Answers4

8

Use Length to determine your string length, then use Substring to take some of it (100 chars) if it is too long:

string aboutme = DT1["UserBody"] != null ? DT1["UserBody"].ToString() : ""; //just in case DT1["UserBody"] is null
lblAboutMe.Text = aboutme.Length > 100 ? aboutme.Substring(0,100) + "..." : aboutme;
Ian
  • 30,182
  • 19
  • 69
  • 107
6

Do it with String.Substring(startIndex, lenght):

lblAboutMe.Text = DT1["UserBody"].ToString().Substring(0, 100) + " ...";

MSDN - Substring

If you want full words try following code. It determines null values and if it's larger than 100 chars. Than it makes shure a space is at the end:

int maxLength = 100;
string body = DT1["UserBody"] != null ? DT1["UserBody"].ToString() : "";

if (!string.IsNullOrEmpty(body))
{
    if(body.Length > maxLength)
    {
        body = body.Substring(0, maxLength);
        // if you want to have full words
        if (body.Contains(" "))
        {
            while (body[body.Length - 1] != ' ')
            {
                body = body.Substring(0, body.Length - 1);
                if(body.Length == 2)
                {
                    break;
                }
            }
        }
        lblAboutMe.Text = body + "...";
    }
    else
    {
        lblAboutMe.Text = body;
    }
}
M. Schena
  • 2,039
  • 1
  • 21
  • 29
  • Honnestly, there is something wrong with this anwer... starting at `body.Length = body.Substring(0, maxLength)`, continuing with the `while` loop that should loop until it throws because `body.length - 2` is below zero (or is `length` different from `Length`?) and let me restate your starting sentence: `Substring` takes a *length* as second parameter, not an end index. Also, checking `string.IsNullOrEmpty(body)` after calling `DT1["UserBody"].ToString()` is eigher error-prone or useless. – grek40 Jan 30 '16 at 08:18
  • You are right about `length`, i wrote it wrong. And that `DT1["UserBody"] != null` should called first to determine that `toString()` won't fail. I changed the code now, thank you, I am also of your opinion of the first sentence, but so it's written on the MSDN-Page – M. Schena Feb 01 '16 at 07:35
  • Maybe I didn't explain the `Substring` issue clear enough.. Substring does take a length parameter, so your code `body.Substring(body.Length - 2, body.Length - 1)` happens to throw an exception or returns a string with a length of `body.Length - 1`. Test your code with a string that starts with a space and contains > 100 characters, then the problem should become clear. – grek40 Feb 01 '16 at 07:47
  • Ok thanks for you explanation. I got it now i think. Changed the code again. – M. Schena Feb 01 '16 at 07:57
  • Really now? please just compile your code before saying "I got it". After fixing the compile-time error, continue with debugging as I already described and when you fixed the runtime exception, you may be good to go – grek40 Feb 01 '16 at 08:14
  • I ment i got it with Substring.. Ok shame on me, had it in mind to compare with chars, but didn't change it.. and messed up with arraylogic on monday-morning.. thx buddy. I got it now. :) – M. Schena Feb 01 '16 at 08:22
1

Please also check for Null or empty string

 string aboutme = Convert.ToString(DT1["UserBody"]);

    if (!string.IsNullOrEmpty(aboutme))
    {
        lblAboutMe.Text = aboutme.Length > 100 ? aboutme.Substring(0, 100) +"..." : aboutme;
    }
  • If *DT1["UserBody"]*'s value is null, exception will occur by your code. You can't convert *null* to *string*. Instead, *Dt1["UserBody"] != null* is correct and more simple. Also, before answering to question, please make sure that nobody else didn't answered already, using the same style (in your case it is "check for Null"). – Khazratbek Jan 29 '16 at 06:42
  • Convert.ToString() handles null, while ToString() doesn't. – vikas singh aswal Jan 29 '16 at 06:55
  • sorry, my fault ;) I saw the *convert*, but I thought only about *.ToString()*. Sometimes I have such bugs xD – Khazratbek Jan 29 '16 at 07:06
1

Basically, you use Substring but be aware of short texts with less than 100 characters

string test = /* your full string */;
string result = test.Substring(0, Math.Min(test.Length, 100)) + " ...";

If you want to cut at spaces, use IndexOf or if you want to consider all kinds of whitespace, you can do something along the lines of the following:

string result = test.Substring(0, Math.Min(test.Length, 100));
if (test.Length > 100)
{
    result += new string(test.Substring(100).TakeWhile(x => !char.IsWhiteSpace(x)).ToArray()) + " ...";
}
grek40
  • 13,113
  • 1
  • 24
  • 50