我與導航屬性設置這樣一個超級鏈接:如何限制文本字符串中的評估和演示
NavigateUrl='<%# Eval("My Text") %>'
如何限制字符串爲140個字符? 我試過這個Eval(「My Text」)。ToString()。Substring(0,140)但是如果字符串長度少於140個字符,它會引發異常。
我與導航屬性設置這樣一個超級鏈接:如何限制文本字符串中的評估和演示
NavigateUrl='<%# Eval("My Text") %>'
如何限制字符串爲140個字符? 我試過這個Eval(「My Text」)。ToString()。Substring(0,140)但是如果字符串長度少於140個字符,它會引發異常。
然而另一可能性:
Eval("My Text").ToString().PadRight(140).Substring(0,140).TrimEnd()
編輯:
我喜歡LINQ,太:
Eval("My Text").ToString().Take(140).Aggregate("", (x,y) => x + y)
你可以嘗試截斷方法,如下所示:
由源參數之前簡單地增加this
關鍵字將其轉換爲一個擴展方法。這是一個比較繞口的方法,但可能是在價值的情況下,你需要重新使用別的地方...
在你的情況,你必須:
NavigateUrl='<%# Eval("My Text").ToString().Truncate(140) %>'
完全控制檯測試應用程序:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string test1 = "A really big string that has more than 140 chars. This string is supposed to be trunctaded by the Truncate extension method defined in class StringTool.";
Console.WriteLine(test1.Truncate(140));
Console.ReadLine();
}
}
/// <summary>
/// Custom string utility methods.
/// </summary>
public static class StringTool
{
/// <summary>
/// Get a substring of the first N characters.
/// </summary>
public static string Truncate(this string source, int length)
{
if (source.Length > length)
{
source = source.Substring(0, length);
}
return source;
}
/// <summary>
/// Get a substring of the first N characters. [Slow]
/// </summary>
public static string Truncate2(this string source, int length)
{
return source.Substring(0, Math.Min(length, source.Length));
}
}
}
輸出:
A really big string that has more than 140 chars. This string is supposed to be
trunctaded by the Truncate extension method defined in class
哎呀我喜歡LINQ:
string.Concat('<%# Eval("My Text") %>'.ToString().Where((char, index) => index < 140))
使用它(:
< % # Eval("MyText").ToString().Length <= 30 ? Eval("MyText") : Eval("MyText").ToString().Substring(0, 30)+"..." % >
類似至 Leniel的答案,但扭曲....有時我喜歡追加一個省略號來演示顯示的字符串已被截斷。
/// <summary>
/// Converts the value of the specified string to a truncated string representation
/// </summary>
/// <param name="source">The specified string</param>
/// <param name="length">Integer specifying the maximum number of characters to retain from the specified string.</param>
/// <param name="appendEllipsis">Determines whether or not to append an ellipsis to the truncated result. If the specified string is shorter than the length parameter the ellipsis will not be appended in any event.</param>
/// <returns>A truncated string representation of the specified string.</returns>
public static String Truncate(this String source, int length, bool appendEllipsis = false)
{
if (source.Length <= length)
return source;
return (appendEllipsis)
? String.Concat(source.Substring(0, length), "...")
: source.Substring(0, length);
}
也許寫一個擴展方法? –