我知道這是一個老問題,但答案的緣故:
public static class Extensions
{
/// <summary>
/// Truncate a value if it is a string.
/// </summary>
/// <param name="value">The value to check and truncate.</param>
/// <param name="length">The length to truncate to.</param>
/// <param name="appendEllipses">Append ellipses to the end of the value?</param>
/// <returns>A truncated string, if not a string the object value.</returns>
public static object Truncate(this object value, int length, bool appendEllipses = true)
{
// Are we dealing with a string value?
var result = value as string;
// Yes? truncate, otherwise pass through.
return result != null ? Truncate(result, length, appendEllipses) : value;
}
/// <summary>
/// Truncate a value if it is a string.
/// </summary>
/// <param name="value">The value to check and truncate.</param>
/// <param name="length">The length to truncate to.</param>
/// <param name="appendEllipses">Append elipses to the end of the value?</param>
/// <returns></returns>
public static string Truncate(this string value, int length, bool appendEllipses = true)
{
var result = value;
// Too Long?
if (value.Length > length)
{
// Truncate.
result = value.Substring(0, length);
// Add Ellipses, if needed.
if (appendEllipses) { result = result + " ..."; }
}
return result;
}
}
你可以你像這樣的第二種方法:
<%# Eval("Description").ToString().Truncate(10) %>
或者爲了避免混亂,你可以使用第一種方法像這樣:
<%# Eval("Description").Truncate(10) %>
我不是100%關於添加擴展方法到對象類,往往是一個痛無處不在,因此我爲什麼選擇它。使用eval
嘗試(「說明」)。字符串(0,100) –
我已經試過這一個,但它會導致一個問題,因爲我的一些字符串必須少於100個字符 – HummingbirdHolly
檢查長度則**如果textbox1.text.Length > 100 - .... Substring(0,100)** – Computer