Tuesday, March 15, 2011

Truncate a text field in Gridview

Call a function from a control that supports databinding events (such as a label).

The example below truncates text where it is found to be greater than 50 in length and adds ... to the end.

The controls refers to a function in the backend by the name of TruncateString.

Source:
<asp:TemplateField HeaderText="Desc2">
<ItemTemplate>

<asp:Label ID="Label1" runat="server" 
Text='<%# TruncateString(DataBinder.Eval(Container.DataItem,"Description").ToString()) %>'>
</asp:Label>

</ItemTemplate>
</asp:TemplateField>

Code:
Protected Function TruncateString(ByVal TheText As String) As String
        If TheText.Length > 50 Then
            Return TheText.Substring(0, 50) & " ..."
        Else
            Return TheText
        End If
    End Function

No comments:

Post a Comment