Home > C#, Software Development > Limiting ASP.NET GridView Text

Limiting ASP.NET GridView Text

The ASP.NET GridView control offers a large amount of parameters for customization. Yet in some cases we need to go further for realizing specific goals.
One such feature was needed by a customer who had to display text in a grid view that would easily exceed the amount of column space. What are the possible solutions here?

  1. The most basic and least flexible would be to truncate any text exceeding a set limit of characters by applying SUBSTRING in the database query.
  2. The other option would be using a TemplateField, which results in a lot of coding overhead, especially if you have to incorporate markup for the insert and update events as well.
  3. Depending on your needs, using the CSS text-overflow:ellipsis could be a compact solution, yet it is only supported by Internet Explorer (some kind of workaround for FireFox exists).
  4. Perhaps the most elegant approach would be the subclassing of the existing BoundField, which already has all the features ready for inserting and updating. Although we only print the first few characters of the column text, we would give the user an additional feature at hand that allows him to view the whole text by hovering the cursor over the short text.

The class EllipsisTextField extends BoundField by one property that reflects the maximum abount of characters to be displayed. If left empty, the control behaves identical with the BoundField class, so it is backwards compatible.

public class EllipsisTextField : BoundField
{
    public int? MaxChars
    {
        get { return this.ViewState[ "MaxChars" ] as int?; }
        set { this.ViewState[ "MaxChars" ] = value; }
    }
 
    protected override string FormatDataValue( object dataValue, bool encode )
    {
        string sLong = dataValue as string;
        if ( this.MaxChars.HasValue && !String.IsNullOrEmpty( sLong ))
        {
            string sShort = sLong;
            if ( sLong.Length > this.MaxChars.Value )
            {
                sShort = sLong.Substring( 0, this.MaxChars.Value ) + "...";
                sLong = HttpUtility.HtmlEncode( sLong );
                sShort = HttpUtility.HtmlEncode( sShort );
 
                dataValue = "<div title=\"" + sLong + "\" style=\"white-space: nowrap;\">" + sShort + "</div>";
                return base.FormatDataValue( dataValue, false );
            }
        }
        return base.FormatDataValue( dataValue, encode );
    }
}

We override the FormatDataValue method in order to execute our own rendering code. Inside, we truncate the original string if necessary, add ellipses and then add short and long versions to a DIV. When set as the title, any mouse over action will render the full code as a tooltip.

  1. No comments yet.
  1. No trackbacks yet.


− 5 = one