在C#代码隐藏

时间:2016-01-29 06:15:21

标签: c# asp.net code-behind

我的代码隐藏中有这一行:

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

没问题。但是现在,我们只想显示段落的开头,然后是省略号。所以,而不是:

  

请阅读所有内容,因为我讨厌与没有这样做的人浪费时间。如果   你有穆斯林的问题请继续,因为我没有。我曾经   练习伊斯兰教,虽然我不再做,但我仍然尊重和恨   无知的人通过追随媒体或耻辱而不是   体验它或与穆斯林交谈以教育自己   它。参考本简介后面的禁毒政策,是的,   锅/大麻算作药物,对我来说是不,所以请继续。   我知道接下来会让我看起来很冷,但我真的很温暖   爱,非常专注于正确的,我只是厌倦了被玩   并且理所当然/有利于。人们撒谎太多而无视   我说的很多我不想要的。我被告知多次   我所寻求的是太多了。

我们想要第一个,比方说100个字符,然后用省略号跟着它。所以,像:

  

请阅读所有内容,因为我讨厌与没有这样做的人浪费时间。如果   你有穆斯林的问题请继续,因为我没有。我曾经   练习伊斯兰教,虽然我不再做,但我仍然尊重和恨   无知的人通过追随媒体或耻辱而不是   体验它或与穆斯林交谈以教育自己......

我们如何在代码隐藏中执行此操作?我觉得这很容易(因为它在Access中很容易),但我还是这种语言的新手。

4 个答案:

答案 0 :(得分:8)

使用Length确定string长度,然后使用Substring获取部分长度(100个字符),如果它太长:

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;

答案 1 :(得分:6)

使用String.Substring(startIndex, lenght)执行此操作:

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

MSDN - Substring

如果您想要完整的单词,请尝试以下代码。它确定空值以及它是否大于100个字符。最终会让舒尔成为一个空间:

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;
    }
}

答案 2 :(得分:1)

还请检查Null或空字符串

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

    if (!string.IsNullOrEmpty(aboutme))
    {
        lblAboutMe.Text = aboutme.Length > 100 ? aboutme.Substring(0, 100) +"..." : aboutme;
    }

答案 3 :(得分:1)

基本上,您使用Substring但要注意少于100个字符的短文

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

如果你想在空格处剪切,请使用IndexOf,或者如果你想考虑所有类型的空白,你可以按照以下方式做一些事情:

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()) + " ...";
}
相关问题