在SSRS中使用省略号截断文本框内容

时间:2014-06-19 12:38:22

标签: reporting-services textbox ssrs-2008 overflow ellipsis

默认情况下,当SSRS中文本框的内容溢出文本框的宽度时,文本框将垂直增长以容纳其内容。通过将文本框的“CanGrow”属性设置为“False”,可以关闭此功能。

然而,这突然切断了内容,这并不理想。

我正在寻找一种方法来清楚地向用户显示文字太宽而无法容纳文本框。在过去,我一直在使用一个简单的表达式来添加省略号“...”,当文本字符串的长度高于某个固定数字时:

=Iif(Len(Fields!CustomerName.Value) > 25, 
     Left(Fields!CustomerName.Value,23) + "...", 
     Fields!CustomerName.Value)

但是当客户名称包含大写字母,小写字母,标点符号和其他使得单个字符像素宽度变化很大的东西时,这种方法效果不佳。

理想情况下,文本框控件的某些属性允许报表开发人员在文本不适合文本框时添加省略号。

有没有人对更优雅的方法有任何建议?

1 个答案:

答案 0 :(得分:8)

我提出的另一个解决方案是使用VB.NET,特别是TextRenderer.MeasureText()函数。

为了完成这项工作,我在报告中添加了以下代码:

Public Function TextWidth(str As String) AS Double
    'Returns the width, in pixels, of a string, assuming Tahoma size 8.
    Dim size As System.Drawing.SizeF
    Dim font As New system.Drawing.Font("Tahoma", 8)
    size = System.Windows.Forms.TextRenderer.MeasureText(str, font)
    TextWidth = size.Width
End Function

Public Function TextCap(str As String, maxWidth As Integer, Optional suffix As String = "") As String
    'Truncates a string to fit within maxWidth pixels, optionally adding a suffix string if
    'any characters were truncated.

    Dim w As Integer, l As Integer
    l = Len(str)
    w = TextWidth(str)
    For i As Integer = 1 To 10
        If (w > maxWidth) Then
            l = (l * maxWidth / w)
            If (l < 0) Then
                l = 0
                Exit For
            End If
            w = TextWidth(Left(str, l) + suffix)
        Else
            Exit For
        End If
    Next i

    If l < Len(str) Then
        TextCap = Left(str, l) + suffix
    Else
        TextCap = Left(str, l)
    End If
End Function

请记住添加对程序集System.Drawing(2.0.0.0)和System.Windows.Forms(2.0.0.0)的引用。 TextWidth函数将使用大小为8的Tahoma字体计算文本字符串的宽度。通过将字体名称和字体大小添加为两个函数的附加参数,可以轻松地将其设置为动态。

从SSRS表达式调用TextCap函数时,如下所示:

=Code.TextCap(Fields!CustomerName.Value, 150, "...")

文本将自动截断为150像素,如果任何字符被截断,将添加后缀参数“...”。

相关问题